实体框架核心无法确定关系

时间:2018-12-18 20:03:06

标签: c# entity-framework-core dbcontext

我有两个对象:“用户”和“关系”。将为我系统中的每个用户创建一个User对象,并将根据每个用户添加为朋友的人数为每个用户创建多个关系。这些对象如下所示

public class User : IdentityUser {}

public class Relationship {
   // User who created the relationship
   public User User {get;set;}

   // User who the creation user is friends with
   public User Friend {get;set;}

   // Enum of Status (Approved, Pending, Denied, Blocked)
   public RelationshipStatus RelationshipStatus {get;set;}

   public DateTime RelationshipCreationDate {get;set;}
}

每个用户在与Relationship.User匹配的地方可以有多个记录,在与Relationship.Friend匹配的地方可以有多个记录。我在OnModelCreating方法中设置了DbContext,如下所示:

protected override void OnModelCreating(ModelBuilder builder)
{
    builder.Entity<Relationship>(relationship =>
    {
        relationship.HasOne(r => r.User).WithMany(u => u.Friends);                
    });            
}

我是Entity的新手,所以这可能微不足道-我所描述的建立关系的过程缺少什么?谢谢!

编辑:更具体地说,这是我遇到的错误:

InvalidOperationException: Unable to determine the relationship represented by navigation property 'Relationship.Friend' of type 'User'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'

编辑2:在重新考虑流程之后,我采用了另一种方法,并使用关系来包括关注者和关注者,而不是集体朋友列表(无论如何更适合我的业务模型)。我是通过以下方式实现的:

public class User : IdentityUser {
  [InverseProperty("Friend")]
  public List<Relationship> Followers {get;set;}

  [InverseProperty("User")]
  public List<Relationship> Following {get;set;}
}

我很好奇,是否有人可以在我的解决方案之外解决最初的问题,但是,这种解决方案目前可以使用,并且似乎最适合我。

2 个答案:

答案 0 :(得分:1)

您是否尝试过向User类添加一个关系列表,即

   public class User : IdentityUser {
       List<Relationship> Relationships {get;set;}
   }

这可能有助于EF充分理解这种关系。

答案 1 :(得分:0)

您似乎正在尝试为many-to-many配置相同的实体。为此,请如下编写UserRelationship模型类:

public class User : IdentityUser 
{
   public List<Relationship> UserFriends { get; set; }
   public List<Relationship> FriendUsers { get; set; }
}

public class Relationship {

   public string UserId {get; set;} // `UserId` type is string as you are using default identity
   public User User {get;set;}

   public string FriendId {get; set;}
   public User Friend {get;set;}

   // Enum of Status (Approved, Pending, Denied, Blocked)
   public RelationshipStatus RelationshipStatus {get;set;}

   public DateTime RelationshipCreationDate {get;set;}
}

然后在模型构建器实体配置中:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Relationship>().HasKey(r => new {r.UserId, r.FriendId});

    modelBuilder.Entity<Relationship>()
    .HasOne(r => r.User)
    .WithMany(u => u.UserFriends)
    .HasForeignKey(r => r.UserId).OnDelete(DeleteBehavior.Restrict);

    modelBuilder.Entity<Relationship>()
    .HasOne(r => r.Friend)
    .WithMany(f => f.FriendUsers)
    .HasForeignKey(r => r.FriendId).OnDelete(DeleteBehavior.Restrict);
}

现在它应该可以正常工作了!

相关问题