Entity Framework many to many relationship with extra field (Database First)

前端 未结 1 1732
误落风尘
误落风尘 2021-01-13 05:35

I have a program using Entity Framework (EF) Database First in the data access layer. I know that in order for EF to auto-generate the navigation properties of a many to man

相关标签:
1条回答
  • 2021-01-13 06:02

    No, you cannot have extra columns in your mapping table in entity framework. Because, having an extra column implies you intend to use it, but Mapping tables are not part of the entity, so, entity framework, no longer treats your mapping table with extra columns as a Mapping table. You will have to manipulate the Mappings manually.

    Lets take example of your classes:

    Project
      - ProjectId (PK)
      - Name
      - ProjectContents
    
    ContentType
      - ContentTypeId (PK)
      - Name
      - ProjectContents
    
    ProjectContentTypeMapping
      - ProjectId (PK)
      - ContentTypeId (PK)
      - OtherRelevantColumn
    

    where ProjectContents is of type ProjectContentTypeMapping

    so whenever you add a Project with Certain ContentType, you would be doing this:

    Project prj = new Project();
    //fill out scalar properties
    ProjectContentTypeMapping pctm = new ProjectContentTypeMapping();
    pctm.ContentTypeId = 1; //or whatever you want, or selected from UI
    
    prj.ProjectContents = new ProjectContentTypeMapping();
    prj.ProjectContents.Add(pctm);
    
    dataContext.Projects.Add(prj);
    

    Now in case of editing (adding ContentTypes) to an existing project, you won't do prj.ProjectContents = new ... rather, you would do it only when it is null i,e,

    if(prj.ProjectContents==null)
       prj.ProjectContents = new ProjectContentTypeMapping();
    

    also, one very very important thing, since now your ProjectContentTypeMapping is no longer a mapping table, so, deleting a Project would give you an error, if its id is being present in ProjectContentTypeMapping table; you will have to remove them manually i.e

    foreach(var pctm in prj.ProjectContents.ToList())
    {
       prj.ProjectContents.Remove(pctm);
       datacontext.ProjectContentTypeMappings.Remove(pctm);
    }
    datacontext.Remove(prj);
    datacontext.SaveChanges();
    
    0 讨论(0)
提交回复
热议问题