1

这是我的代码:

public class RegisteredUser
{
    public virtual int ID { get; set; }
    [Required]
    public virtual string FirstName { get; set; }
    [Required]
    public virtual string LastName { get; set; }
    [Required]
    public virtual string Email { get; set; }
    [Required]
    [DataType(DataType.Password)]
    public virtual string Password { get; set; }
    public virtual string NickName { get; set; }
    [Required]
    [DataType(DataType.Date)]
    public virtual DateTime DOB { get; set; }
    public virtual string Avatar { get; set; }
    public virtual ICollection<Post> Posts { get; set; }
    public virtual ICollection<CommentPost> CommentPosts { get; set; }
    public virtual ICollection<TagPost> TagPosts { get; set; }
    public virtual ICollection<RegisteredUser> Friends { get; set; }
}

public class SocialWeb_BasedApplicationDB : DbContext
{
    public DbSet<RegisteredUser> RegisteredUsers { get; set; }
    public DbSet<Post> Posts { get; set; }
    public DbSet<CommentPost> CommentPosts { get; set; }
    public DbSet<TagPost> TagPosts { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Post>().HasMany(m => m.CommentPost).WithRequired(a => a.Post).WillCascadeOnDelete(false);
        modelBuilder.Entity<RegisteredUser>().HasMany(m => m.TagPosts).WithRequired(a => a.RegisteredUser).WillCascadeOnDelete(false);
        modelBuilder.Entity<RegisteredUser>().HasMany(a => a.Friends).WithMany().Map(a => a.MapLeftKey("UserID").MapRightKey("FriendID").ToTable("Users_Friends"));
    }

Many To May 表已创建,但我不能像我做的那样实际使用它(从 n in Context.User_Friends where n.UserId = 0 select n);

我该怎么办?

4

1 回答 1

0

从 EF 的角度来看,User_Friends 不是一个实体,而是要获取用户的朋友,您必须使用此查询

var friends = from u in Context.RegisteredUsers
              from f in u.Friends
              where u.UserId=0
              select f;

我通常将关系变成显式实体,因为有更多关于这些关系的有用信息,否则无法捕获。

于 2012-12-03T22:06:25.743 回答