我正在创建一个迷你社交媒体,在主页中我必须查看用户朋友的帖子 我有三张桌子
public class Post
{
[Key]
public int Id { get; set; }
public string Date { get; set; }
public string Text { get; set; }
[DisplayName("PicturePath")]
public string PicturePath { get; set; }
public int interests { get; set; }
public int userId { get; set; }
public User user { get; set; }
}
public class User
{
public int Id { get; set; }
[Required]
[MinLength(8)]
[MaxLength(25)]
public string Name { get; set; }
[DisplayName("Profile Picture")]
public string PicturePath { get; set; }
[Required]
public string Specialization { get; set; }
[Required]
public string BirthDate { get; set; }
[Required]
public string Brief { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
[DisplayName("Password")]
public string PasswordHash { get; set; }
[DefaultValue(false)]
public bool EmailConfirmed { get; set; }
public virtual ICollection<Post> Posts { get; set; }
public virtual ICollection<FriendShip> friendShip { get; set; }
public virtual ICollection<ResetPassword> resetPassword { get; set; }
}
public class FriendShip
{
public int Id { get; set; }
public int UserId { get; set; }
public int FriendId { get; set; }
public string FriendShipDate { get; set; }
public User user { get; set; }
}
我正在尝试选择属于登录用户的朋友的帖子。 每个用户都有朋友(在FriendShip表中输入的朋友ID)...所以我想预览朋友的所有帖子。 查询表格会怎样?
假设在您的FriendShip表上,一旦建立了“Friendship”,您将添加两条记录:User-Friend(用户ID =当前用户ID)和Friend-User(用户ID =朋友的User ID)。
对于下面的 lambda 查询,请确保您已将登录用户的 ID 分配给loggedInUserId。
var friendsList = db.FriendShips.Where(f=>f.UserId == loggedInUserId).Select(f=>f.FriendId)ToArray();
List<Post> friendsPosts = db.Posts.Where(p=>friendsList.contains(p.userId))