c# - Code first many to many relationship with attributes in relational table -
i want create relation attributes relational table. below referance code. code create 2 tables bookstudents , bookstudents1. 1 have relation attributes without forigen keys , other creates table without attributes forign keys. how can solve issue?
public class bookstudent { [key, column(order = 0)] public int bookid { get; set; } [key, column(order = 1)] public int studentid { get; set; } public datetime fromdate { get; set; } public datetime todate { get; set; } } public class context : dbcontext { public context() : base("name=defaultconnection") { } public dbset<book> books { get; set; } public dbset<student> students { get; set; } public dbset<bookstudent> bookstudents { get; set; } protected override void onmodelcreating(dbmodelbuilder modelbuilder) { modelbuilder.entity<book>().hasmany<student>(t => t.students).withmany(t => t.books).map(t => { t.mapleftkey("bookid"); t.maprightkey("studentid"); t.totable("bookstudents"); }); } }
in code first many cases not need define explicitly relationship on onmodelcreating. utilize below code solve problem.
public class bookstudent { [key, column(order = 0)] public int bookid { get; set; } [key, column(order = 1)] public int studentid { get; set; } public datetime fromdate { get; set; } public datetime todate { get; set; } //below 2 lines define foreign key public pupil student { get; set; } public book book { get; set; } } public class context : dbcontext { public context() : base("name=defaultconnection") { } public dbset<book> books { get; set; } public dbset<student> students { get; set; } public dbset<bookstudent> bookstudents { get; set; } protected override void onmodelcreating(dbmodelbuilder modelbuilder) { //remove below code //modelbuilder.entity<book>().hasmany<student>(t => t.students).withmany(t => t.books).map(t => //{ // t.mapleftkey("bookid"); // t.maprightkey("studentid"); // t.totable("bookstudents"); //}); } }
c# entity-framework many-to-many code-first dbcontext
No comments:
Post a Comment