草庐IT

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

coder 2024-05-20 原文

我正在尝试映射与同一实体的多对多关系。 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/

有关c# - Entity Framework 核心 : many-to-many relationship with same entity的更多相关文章

随机推荐