I am working on entity to get the posts on user wall of posted by him and posted to him and posted by his friends
For this I have 4 tables
userprofile
post
postcomment
friends
Userprofile table has UserID, UserName, ProfileImg
Post table has PostId, postedby, postedto, message,posteddate
postcomment table has commentid, postid, commentedby, message, commenteddate
friends table has id, Username, friendUserName
and in entity
userprofile to post--- 1 to many
post to postcomment --- 1 to many
userprofile to postcomment--- 1 to many
post to friends --- many to many
I have used the query shown below to get posts posted by him and posted to him... but I am confused on how to include the posts posted by his friends.... please help me in this
var ret = (from post in db.Posts.ToList()
where post.PostedBy == (int)Session["UserID"] ||
post.PostedBy == db.friends.all(something to get friends one by one)||
post.PostedTo == Session["UserName"].ToString()
orderby post.PostedDate descending
select new
{
Message = post.Message,
PostedBy = post.PostedBy,
PostedByName = post.UserProfile.UserName,
ProfileImage = imgFolder + (String.IsNullOrEmpty(post.UserProfile.ProfileImg) ? defaultAvatar : post.UserProfile.ProfileImg),
PostedDate = post.PostedDate,
PostedTo = post.PostedTo,
PostId = post.PostId,
PostComments = from comment in post.PostComments.ToList()
orderby comment.CommentedDate
select new
{
CommentedBy = comment.CommentedBy,
CommentedByName = comment.UserProfile.UserName,
ProfileImage = imgFolder + (String.IsNullOrEmpty(comment.UserProfile.ProfileImg) ? defaultAvatar : comment.UserProfile.ProfileImg),
CommentedDate = comment.CommentedDate,
CommentId = comment.CommentId,
Message = comment.Message,
PostId = comment.PostId
}
}).AsEnumerable();
im returning ret to jquery to dynamically update the posts.... is there any solution or i have to completely change the query ??? I want to get the posts posted to the user and posted by the user and posted by his friends to display on user wall ... what is the best way to do it??
UPDATE
As of now i got this solution... there may be better solution for this.. if any please let me know..
var ret = (from post in db.Posts.ToList()
where post.PostedBy == (int)Session["UserID"] ||
(from frnd in db.friends where frnd.userId == (int)Session["UserID"] select frnd.frndId).Contains(post.PostedBy)||
post.PostedTo == Session["UserName"].ToString()
orderby post.PostedDate descending
select new
{
Message = post.Message,
PostedBy = post.PostedBy,
PostedByName = post.UserProfile.UserName,
ProfileImage = imgFolder + (String.IsNullOrEmpty(post.UserProfile.ProfileImg) ? defaultAvatar : post.UserProfile.ProfileImg),
PostedDate = post.PostedDate,
PostedTo = post.PostedTo,
PostId = post.PostId,
PostComments = from comment in post.PostComments.ToList()
orderby comment.CommentedDate
select new
{
CommentedBy = comment.CommentedBy,
CommentedByName = comment.UserProfile.UserName,
ProfileImage = imgFolder + (String.IsNullOrEmpty(comment.UserProfile.ProfileImg) ? defaultAvatar : comment.UserProfile.ProfileImg),
CommentedDate = comment.CommentedDate,
CommentId = comment.CommentId,
Message = comment.Message,
PostId = comment.PostId
}
}).AsEnumerable();
Related
I'm trying to get a list in a linq with joins and get all events for specific user.
This is the query I have so far:
var runnerObject = from r in _context.Runners
join re in _context.RunnerEvents
on r.RunnerId equals re.RunnerId
join e in _context.Events
on re.EventId equals e.EventId
where r.RunnerId == runnerId
select new RunnerVM
{
RunnerId = r.RunnerId,
FirstName = r.FirstName,
LastName = r.LastName,
UserId = r.UserId,
Events = //get all events in Events table for the runnerId
};
Events should be all entries from Events table for that runner, based on their id which is joined in the RunnerEvents table. How can I get that?
Something like this?
var runnerObject = from r in _context.Runners
join re in _context.RunnerEvents
on r.RunnerId equals re.RunnerId
join e in _context.Events
on re.EventId equals e.EventId
where r.RunnerId == runnerId
select new RunnerVM
{
RunnerId = r.RunnerId,
FirstName = r.FirstName,
LastName = r.LastName,
UserId = r.UserId,
Events = r.Events.Select(e => new Event { }).ToList()
};
I have a table called "UserAnswers".below screenshot contains table data
I want to get data by surveyId and group by CreatedBy column.
for an example
There is a user called "amara#gmail.com".this user contains 4 records for a SurveyId.
I want to get this like below
Answers : [
{"2"},
{"1","0","1","1"},
{"1","2","4","3"},
{"Blue"}]
But my code returns this array for every rows.I meant duplicate records returning.
Here is my code
var qstns = await (from uans in _context.UserAnswers
where uans.SurveyId == id
select new UserAnswersReturnDto
{
UserEmail = uans.CreatedBy,
Qustns = (from ans in _context.UserAnswers
where ans.CreatedBy == uans.CreatedBy
select new UserAnswersSet
{
QNo = ans.QNo,
Ansrs = JsonConvert.DeserializeObject<JArray>(string.IsNullOrEmpty(ans.Answers) ? "[]" : ans.Answers)
}).ToArray()
}).ToListAsync();
So how to solve this issue.I opened many questions for this problem,but no one answered.Please help me.Thanks in advanced
You need to actually group your data before returning:
I used LINQ Lambda notation, but it should be quite easy to translate back to query if you're so inclined:
var qstns = _context.UserAnswers.Where(uans => uans.SurveyId == id)
.GroupBy(uans => uans.CreatedBy)
.Select(grans => new UserAnswersReturnDto {
UserEmail = grans.Key,
Qustions = grans.Select(ans => new UserAnswersSet() {
QNo = ans.QNo,
Ansrs = ans.Answers
}).ToList()
} ).ToList();
I didn't have time to double-check this, but I hope it serves as a guide to help you solve your issue!
There is no group by statement in your linq query.
I´m having trouble understand EF.
I have 2 tables in a N-to-N relationship. When I create the model in Visual Studio I get it like the picture below.
Artist is related to Album, and Album is related to Artist.
In the database I have a table to relate both tables.
My question is:
Why can I add an artist with two albums,
var artist = new Artist { FirstName = "Alan", LastName = "Jackson" };
var album1 = new Album { AlbumName = "Drive" };
var album2 = new Album { AlbumName = "Live at Texas Stadium" };
artist.Albums.Add(album1);
artist.Albums.Add(album2);
context.Artists.Add(artist);
But can´t do the other way around?
var artist1 = new Artist { FirstName = "Tobby", LastName = "Keith" };
var artist2 = new Artist { FirstName = "Merle", LastName = "Haggard" };
var album = new Album { AlbumName = "Honkytonk University" };
artist1.Albums.Add(album);
artist2.Albums.Add(album);
context.Albums.Add(album);
context.SaveChanges();
It´s not making sense to me, since both tables in VS model have the Navigation Properties correct, isn´t the same adding to left or right?
In my mind, in the second case EF should add artist1 and artist2 to DB.
Thanks for reading.
FranciscoRC
To expand on Ivan's comment.
With this example:
var artist1 = new Artist { FirstName = "Tobby", LastName = "Keith" };
var artist2 = new Artist { FirstName = "Merle", LastName = "Haggard" };
var album = new Album { AlbumName = "Honkytonk University" };
artist1.Albums.Add(album);
artist2.Albums.Add(album);
context.Albums.Add(album);
Prior to SaveChanges, album.Artists hasn't been set with anything, and all EF has to go on is what you've set on album.
In your case, you've created 2x artist objects, and 1 album. You've associated the album to the artist, but you've only notified EF of the album to be saved. Just as with POCOs just because an artist has an album and an album has an artist, setting the album on an artist doesn't automatically set the artist property on an album. EF does this behind the scenes provided that it sees the related entities on the entity(ies) you add to the context.
So the following should work:
var artist1 = new Artist { FirstName = "Tobby", LastName = "Keith" };
var artist2 = new Artist { FirstName = "Merle", LastName = "Haggard" };
var album = new Album { AlbumName = "Honkytonk University" };
album.Artists.Add(artist1);
album.Artists.Add(artist2);
context.Albums.Add(album);
Prior to SaveChanges being called, artist1.Album will be null because you haven't set anything. After SaveChanges, artist1 & 2 .Album will reference to your new entity because EF resolved the Artists collection on the album and wired up the related references. (Even though Artists 1 & 2 were not added to the context explicitly.)
Show comments of every one who posted it in my page
This is giving blank page
Where am i going wrong
FB.api({
method: 'fql.multiquery',
queries: {
query1: 'SELECT post_fbid, fromid, text, time FROM comment WHERE post_id="'+postID +'"',
query2: 'SELECT id, name, url, pic FROM profile WHERE id IN (SELECT fromid FROM #query1)'
}
});
</script>
<script>
function(response) {
var comments = response[0].fql_result_set;
var users = response[1].fql_result_set;
//loop through the comments
for(var i = 0, j = comments.length; i<j; i++){
for(var x = 0, y = users.length; x<y; x++){
if(comments[i].fromid == users[x].id){
//we have a match, this comment is from user users[x]
//process users[x]
//break the inner for loop, since we already have a match
}
}
}
}
Are you using the new Facebook comments (“migrated”)?
Perhaps consider using the graph API instead:
https://graph.facebook.com/comments/?ids=http://example.com/
Here is my code:
string code = Request.QueryString["code"];
string appId = "x";
string appSecret = "x";
if (code == "" || code == null)
{
//request for authentication
Response.Redirect("https://graph.facebook.com/oauth/authorize?client_id=" + appId + "&redirect_uri=http://localhost:62543/&scope=email,read_stream");
}
else
{
var fb = new MyFB();
fb.ApplicationSecret = appSecret;
fb.ApplicationID = appId;
string accessToken = fb.GetAccessToken(code);
fb.AccessToken = accessToken;
var fbc = new FacebookClient(accessToken);
dynamic streams = fbc.Query("select post_id from stream where permalink = 'http://www.facebook.com/kevin.clough/posts/882439437244'");
Response.Write(streams.Count);
dynamic results = fbc.Query("select comments, likes from Post where id = " + streams.post_id);
foreach (dynamic comment in results.comments)
{
Response.Write(comment.from.name + ", " + comment.message + "<br/>");
}
}
Getting this error "A session cannot be used when querying the stream table with a viewer_id that is a different from the session owner."
How do I authorize this session to view my own data?
So the first problem I see is that the query is not valid. You have:
select post_id from stream
where permalink = 'http://www.facebook.com/kevin.clough/posts/882439437244'
Per the Facebook documentation here you can only query the stream table using the columns post_id, app_id, source_id, filter_key, and xid.
So you should change your first query to this (using post ID '19292868552_118464504835613' as an example):
select post_id from stream where post_id = '19292868552_118464504835613'
Alternatively, you could do the same thing with the graph using the post id:
dyanmic post1 = fbc.Get("19292868552_118464504835613");
Your second query is wrong mainly because you are querying a table that doesn't exist.
select comments, likes from Post where id = " + streams.post_id
There is no such FQL table 'Post'. I am not sure what the goal of this is, but if you want to get the likes and comments I think it would be easier to use the Graph API.
Comments:
dynamic comments = fbc.Get("19292868552_118464504835613/comments");
Likes:
dynamic likes = fbc.Get("19292868552_118464504835613/likes");
Here is Facebook's documentation on the Post Graph API: http://developers.facebook.com/docs/reference/api/post/
EDIT:
To determine the stream items of a user you will want to read their feed. You can do this using the Graph API also.
dynamic feed = fbc.Get("me/feed");
foreach (dynamic post in feed.data) {
var post_id = post.id;
}
This will get you the most recent posts of the user. From there you can loop through them to find the one you want to get more details.