简体   繁体   中英

Access to Many-to-Many table

I have two tables, Project and BOM . Their relationship is many-to-many .

When I check my Migration class, I can see the below code that was automatically generated.

CreateTable(
    "dbo.ProjectBOMs",
    c => new
        {
            Project_Id = c.Int(nullable: false),
            BOM_Id = c.Int(nullable: false),
        })
    .PrimaryKey(t => new { t.Project_Id, t.BOM_Id })
    .ForeignKey("dbo.Projects", t => t.Project_Id, cascadeDelete: true)
    .ForeignKey("dbo.BOMs", t => t.BOM_Id, cascadeDelete: true)
    .Index(t => t.Project_Id)
    .Index(t => t.BOM_Id);

However, when I try to access this table using the following method, it's not showing up.

using(var db = new ApplicationDbContext())
{
    db.ProjectBOMs //<== there's no ProjectBOMs in db
}

Since ProjectBOMs table has already been automatically generated, do I have to write the following code again to be able to access the table?

modelBuilder.Entity<Project>()
    .HasMany<BOM>(x => x.BOMs)
    .WithMany(x => x.Projects)
    .Map(x =>
    {
        x.MapLeftKey("Project_Id");
        x.MapRightKey("BOM_Id");
        x.ToTable("ProjectBOMs");
    });

I think the issue might be that the table isn't an entity in itself in your model, it's just the result of how the many-many relationship between Project and BOM is represented in a SQL database (ie with a joining table).

Do you need to access it because you need additional columns in the table? If so this question and the top voted answer look pretty useful.

The if the table ProjectBOMs consists only of the Forign Key columns to Projects and BOMs then the table is NOT imported. It will result in a Project Collection on the BOMS and a BOM Collection on Projects, but will not be available as a stand alone entity.

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