gpt4 book ai didi

c# - Entity Framework 核心无法确定关系

转载 作者:行者123 更新时间:2023-11-30 17:28:00 24 4
gpt4 key购买 nike

我有两个对象:用户和关系。为我系统的每个用户创建一个用户对象,并根据他们添加为 friend 的人数为每个用户创建多个关系。对象如下所示

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 的记录。我的 DbContext 在 OnModelCreating 方法中设置如下:

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

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

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

InvalidOperationException:无法确定由类型为“User”的导航属性“Relationship.Friend”表示的关系。手动配置关系,或使用“[NotMapped]”属性或使用“OnModelCreating”中的“EntityTypeBuilder.Ignore”忽略此属性

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

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

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

我很好奇是否有人能在我的解决方案之外解决原始问题,但是,这目前有效并且似乎最适合我。

最佳答案

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

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

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

关于c# - Entity Framework 核心无法确定关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53840236/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com