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

时间:2015-03-05 13:36:43

标签: c# sql entity-framework asp.net-mvc-4

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

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

1 个答案:

答案 0 :(得分:0)

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