简体   繁体   中英

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 :

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.

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 :

        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<> . They need to be ICollection<> . Once you fix that, Entity Framework will pick up the M2M and create the necessary join table. 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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