Entity Framework Code First Use foreign key as part of composite primary key -
using code first, created model representing donor. used migration generate table store donor objects. used annotations specify primary key composite of 2 properties of model, name , teamid.
i added navigation property model called hourlysnapshots icollection<hourlysnapshot> representing one-to-many relationship. (hourlysnapshot domain model created.) ran migration , generated table store hourlysnapshot objects. expected, added 2 columns weren't in model store foreign key composed of name , teamid.
in order initialize hourlysnapshots table, included conventional id property in hourlysnapshot object used primary key. i'm trying switch primary key of hourlysnapshots table id column composite of foreign key (which composite of name , teamid) , property of hourlysnapshot called timestamp. in other words, make composite of 3 columns name, teamid, , timestamp.
can think of way code first? can opening table definition , editing there, adhere code first workflow, migrations include changes.
after more research, able accomplish fluent api. don't think it's possible using annotations or conventions. here ended in applicationdbcontext class...
public dbset<donor> donors { get; set; } public dbset<hourlysnapshot> hourlysnapshots { get; set; } public dbset<dailysnapshot> dailysnapshots { get; set; } protected override void onmodelcreating(dbmodelbuilder modelbuilder) { modelbuilder.entity<donor>() .haskey(d => new { d.name, d.teamid }); modelbuilder.entity<hourlysnapshot>() .haskey(s => new { s.name, s.teamid, s.timestamp }); modelbuilder.entity<donor>() .hasmany(d => d.hourlysnapshots) .withoptional() .hasforeignkey(s => new { s.name, s.teamid }); modelbuilder.entity<dailysnapshot>() .haskey(s => new { s.name, s.teamid, s.timestamp }); modelbuilder.entity<donor>() .hasmany(d => d.dailysnapshots) .withoptional() .hasforeignkey(s => new { s.name, s.teamid }); base.onmodelcreating(modelbuilder); }
Comments
Post a Comment