繁体   English   中英

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

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

我有一个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; }
}

代码首先忽略了多对多的关系,没有创建表CompanySectors

我通过在迁移中手动编码表来解决这个问题

    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);

但是,当我向公司添加一个新的部门时,新的部门没有插入表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();

如何在同一个表中拥有多对多关系和一对一关系。 提前致谢

您的问题在于使您的导航属性类型为List<> 它们需要是ICollection<> 解决之后,Entity Framework将选择M2M并创建必要的连接表。 自己手动添加表没有做任何事情,因为实体框架仍然不知道这种关系(事实证明它没有创建表本身)。

暂无
暂无

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

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