我正在构建类似于facebook的webapp。我想查询数据库,以便我从当前登录用户的朋友那里得到帖子(类似于facebook的“home”) 好的是模型
public User()
{
this.Friends = new HashSet<Friend>();
this.Friends1 = new HashSet<Friend>();
this.Posts = new HashSet<Post>();
}
public int userID { get; set; }
public System.Guid user_Unique_ID { get; set; }
public string username { get; set; }
public string profilePicUrl { get; set; }
public virtual ICollection<Friend> Friends { get; set; }
public virtual ICollection<Friend> Friends1 { get; set; }
public virtual ICollection<Post> Posts { get; set; }
public partial class Friend
{
public int friendshipID { get; set; }
public int userfrID { get; set; }
public int friendID { get; set; }
public virtual User User { get; set; }
public virtual User User1 { get; set; }
}
public partial class Post
{
public int postID { get; set; }
public int userpostID { get; set; }
public System.DateTime postedOn { get; set; }
public string text { get; set; }
public int likes { get; set; }
public virtual User User { get; set; }
}
我尝试的是,创建一个viewmodel:
public class HomePosts
{
public int postID { get; set; }
public int userID { get; set; }
public int userpostID { get; set; }
public string username { get; set; }
public string text { get; set; }
public System.DateTime postedOn { get; set; }
public int likes { get; set; }
public int userfrID { get; set; }
public int friendID { get; set; }
}
这是我的疑问:
using (var context = new ASPNETDBEntities())
{
MembershipUser x = Membership.GetUser();
User wad = context.Users.Where(u => u.user_Unique_ID == (System.Guid)x.ProviderUserKey).SingleOrDefault();
int id = wad.userID;
var allposts = (from u in db.Users
join f in db.Friends
on u.userID equals f.userfrID
where f.userfrID == id
join p in db.Posts
on f.friendID equals p.userpostID
select new HomePosts
{
friendID = f.friendID,
likes = p.likes,
postedOn = p.postedOn,
postID = p.postID,
text = p.text,
userfrID = f.userfrID,
userID = u.userID,
username = u.username, <-- this is the problem
userpostID = p.userpostID
}).OrderByDescending(u => u.postedOn).ToList();
return View(allposts);
}
问题是,对于每个帖子,它显示当前登录用户的用户名,而不是发布该帖子的朋友的用户名。我需要海报的用户名(朋友)。 有什么建议吗?
答案 0 :(得分:2)
好的,你可以试试这个:
from f in db.Friends
join u in db.Users
on f.friendID equals u.userID
where f.userfrId = id
join p in db.Posts
on f.friendID equals p.userpostID
select new HomePosts
{
friendID = f.friendID,
likes = p.likes,
postedOn = p.postedOn,
postID = p.postID,
text = p.text,
userfrID = f.userfrID,
userID = u.userID,
username = u.username,
userpostID = p.userpostID
}
或者,如果您的EF设置正确,您可以这样做:
var posts = db.Posts.Where(p => p.User.Any(u => u.Friends.Any(f => f.userfrID == id))).Select(p => new HomePosts
{
// your selections
}
)
答案 1 :(得分:0)
不应该这部分
join p in db.Posts
on f.friendID equals p.userpostID
是:
join p in db.Posts
on u.userID equals p.userpostID
除非我误解,否则听起来就像你说的那样:
在帖子的用户ID上加入帖子表 - &gt;当前用户 - &gt;朋友 - &gt;朋友ID(循环回当前用户)