简体   繁体   English

合并与一对一关系的多对多关系

[英]Merge Many to many relationship with a one to one relationship

I have a Company class with a list of Sectors and one Main Sector : 我有一个Company类,其中包含一个Sectors列表和一个Main Sector

public class Company 
{
   public virtual List<Sector> Sectors {get; set;}
   [DisplayName("MainSectorId")]
   [ForeignKey("MainSector")]
   public virtual int? MainSectorId { get; set; }
   public virtual Sector MainSector { get; set; }
}

public class Sector
{
  public List<Company> Companies {get; set; }
}

the code first ignores the many to many relationship, the table CompanySectors was not created. 代码首先忽略了多对多的关系,没有创建表CompanySectors

I fixed that by coding the table manually in the migration 我通过在迁移中手动编码表来解决这个问题

    CreateTable(
        "dbo.CompanySectors",
        c => new
            {
                Company_Id = c.Int(nullable: false),
                Sector_Id = c.Int(nullable: false),
            })
        .PrimaryKey(t => new { t.Company_Id, t.Sector_Id })
        .ForeignKey("dbo.Companies", t => t.Company_Id, cascadeDelete: true)
        .ForeignKey("dbo.Sectors", t => t.Sector_Id, cascadeDelete: true)
        .Index(t => t.Company_Id)
        .Index(t => t.Sector_Id);

But the when I add a new sector to the company, the new sector is not inserted into the table CompanySectors : 但是,当我向公司添加一个新的部门时,新的部门没有插入表CompanySectors

        companyDB.MainSector = sectorDB;
        companyDB.MainSectorId = sectorDB.Id;
        EntityRepository.dbContext.Entry(companyDB).State = System.Data.Entity.EntityState.Modified;
        EntityRepository.dbContext.Entry(sectorDB).State = System.Data.Entity.EntityState.Modified;
        EntityRepository.dbContext.SaveChanges();

How can I have a many to many relation ship and a one to one in the same table. 如何在同一个表中拥有多对多关系和一对一关系。 Thanks in advance 提前致谢

Your problem is in making your navigation properties of type, List<> . 您的问题在于使您的导航属性类型为List<> They need to be ICollection<> . 它们需要是ICollection<> Once you fix that, Entity Framework will pick up the M2M and create the necessary join table. 解决之后,Entity Framework将选择M2M并创建必要的连接表。 Adding the table manually, yourself, did nothing, because Entity Framework still had no knowledge of the relationship (as evidenced by the fact that it didn't create the table itself). 自己手动添加表没有做任何事情,因为实体框架仍然不知道这种关系(事实证明它没有创建表本身)。

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

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