[英]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.