简体   繁体   English

实体框架6.1.2多对多

[英]Entity Framework 6.1.2 Many to Many

I am having trouble with entity framework 6.1.2. 我在使用实体框架6.1.2时遇到麻烦。 I'm sure this will have been covered before but I cant find it anywhere. 我敢肯定这会被覆盖过,但是我在任何地方都找不到。 On building the database entity framework wont create the relationships for the two list items I have because I have them declared as single entities above. 构建数据库实体框架时,不会为我拥有的两个列表项创建关系,因为我在上面将它们声明为单个实体。

Is there any work around for this? 有什么解决办法吗?

public class SomeClass
{
    public TeamMember LeadPartner { get; set; }
    public Team Team { get; set; }
    public List<TeamMember> OtherTeamMembers { get; set; }
    public List<Team> OtherTeams { get; set; }
}

Sorry if this has been asked before I really couldn't find anything on it. 抱歉,在我真的找不到任何东西之前是否有人问过这个问题。

Most likely there is ambiguity in the other classes. 其他类很可能存在歧义。 For instance if you have a List<SomeClass> defined in Team , EF can't be sure whether this property is to partner with public Team Team (which would create a one-many relationship) or public List<Team> OtherTeams (creating a many-many relationship). 例如,如果您在Team定义了List<SomeClass> ,则EF无法确定此属性是与public Team Team (这将创建一对多关系)还是与public List<Team> OtherTeams (创建一个多对多关系)。 Either is valid. 两者均有效。

To resolve the ambiguity, add an [InverseProperty("OtherTeams")] annotation to the List<SomeClass> in the other classes. 若要解决歧义,请在其他类的List<SomeClass>中添加[InverseProperty("OtherTeams")]批注。

Also, best practice is to expose the property as an ICollection<T> rather than a List<T> , creating a new List<T> or whatever in the constructor. 同样,最佳实践是将属性公开为ICollection<T>而不是List<T> ,以创建new List<T>或构造函数中的任何内容。 This allows you to vary implementation later, for instance use a HashSet<T> instead. 这允许您稍后更改实现,例如,改用HashSet<T>

Add the mapping in your DbContext.OnModelCreating override similar to the following: 在您的DbContext.OnModelCreating覆盖中添加映射,类似于以下内容:

modelBuilder.Entity<SomeClass>()
            .HasMany<TeamMember>(sc => sc.OtherTeamMembers)
            .HasMany();
         // .HasMany(tm => tm.SomeClassNavigationPropertyList);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM