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


i have program using entity framework (ef) database first in data access layer. know in order ef auto-generate navigation properties of many many relationship, mapping table needs contain composite primary key:

project   - projectid (pk)   - name  contenttype   - contenttypeid (pk)   - name  projectcontenttypemapping   - projectid (pk)   - contenttypeid (pk) 

in case works fine, , can access projects contenttypes , other way around navigation properties.

however have requirement have fields particular relation between projects , contenttypes, , columns in projectcontenttypemapping table. once add these loose navigation properties, , ef shows mapping table in designer.

is there way can manually configure mapping between these 2 tables in ef (database first)? alternatively, how can represent this? thinking of maybe having "metadata" table fk mapping table, looks "hacky" me...

thanks

no, cannot have extra columns in mapping table in entity framework. because, having column implies intend use it, mapping tables not part of entity, so, entity framework, no longer treats mapping table columns mapping table. have manipulate mappings manually.

lets take example of classes:

project   - projectid (pk)   - name   - projectcontents  contenttype   - contenttypeid (pk)   - name   - projectcontents  projectcontenttypemapping   - projectid (pk)   - contenttypeid (pk)   - otherrelevantcolumn 

where projectcontents of type projectcontenttypemapping

so whenever add project contenttype, doing this:

project prj = new project(); //fill out scalar properties projectcontenttypemapping pctm = new projectcontenttypemapping(); pctm.contenttypeid = 1; //or whatever want, or selected ui  prj.projectcontents = new projectcontenttypemapping(); prj.projectcontents.add(pctm);  datacontext.projects.add(prj); 

now in case of editing (adding contenttypes) existing project, won't prj.projectcontents = new ... rather, when null i,e,

if(prj.projectcontents==null)    prj.projectcontents = new projectcontenttypemapping(); 

also, 1 very important thing, since projectcontenttypemapping no longer mapping table, so, deleting project give error, if id being present in projectcontenttypemapping table; have 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(); 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -