gpt4 book ai didi

c# - Entity Framework 核心 : many-to-many relationship with same entity

转载 作者:可可西里 更新时间:2023-11-01 03:07:58 25 4
gpt4 key购买 nike

我正在尝试映射与同一实体的多对多关系。 User实体有一个 IList<User> Contacts 的数据字段,其中存储了用户的联系人/ friend 信息:

public class User : DomainModel
{
public virtual IList<User> Contacts { get; protected set; }
//irrelevant code omitted
}

当我尝试使用 Fluent API 来映射这种多对多关系时,它给我带来了一些麻烦。显然,当我使用 HasMany() 时在 user.Contacts 上属性(property),它没有WithMany()接下来要调用的方法。来自 Visual Studio 的智能感知仅显示 WithOne() , 但不是 WithMany() .

modelBuilder.Entity<User>().HasMany(u => u.Contacts).WithMany() 
// gives compile time error: CS1061 'CollectionNavigationBuilder<User, User>' does not contain a definition for 'WithMany' and no extension method 'WithMany' accepting a first argument of type

那么为什么会这样呢?我在映射这种多对多关系时做错了什么吗?

最佳答案

So why does this happen? Is there anything I did wrong to map this many-to-many relationship?

不,你没有做错任何事。 It's just not supported .当前状态here .

Many-to-many relationships without an entity class to represent the join table are not yet supported. However, you can represent a many-to-many relationship by including an entity class for the join table and mapping two separate one-to-many relationships.

使用 EF-Core,您应该为映射表创建实体。如 UserContactsdocs 中的完整示例,如评论中所述。我还没有实际测试下面的代码,但它应该看起来像这样:

public class UserContacts
{
public int UserId { get; set; }
public virtual User User { get; set; }

public int ContactId { get; set; } // In lack of better name.
public virtual User Contact { get; set; }
}

public class User : DomainModel
{
public List<UserContacts> Contacts { get; set; }
}

还有你的modelBuilder

  modelBuilder.Entity<UserContacts>()
.HasOne(pt => pt.Contact)
.WithMany(p => p.Contacts)
.HasForeignKey(pt => pt.ContactId);

modelBuilder.Entity<UserContacts>()
.HasOne(pt => pt.User)
.WithMany(t => t.Contacts)
.HasForeignKey(pt => pt.UserId);

关于c# - Entity Framework 核心 : many-to-many relationship with same entity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39771808/

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