Is it possible define one-to-many relation in Sql Server and just define and use one side of this relation in entity code first -
if defined one-to-many relation foreign-key constraints in sql server, possible define , use in code-first class definitions in 1 side? example suppose have library , book classes. each library can has many books each book belong 1 library.
public class book { public book() { } public int bookid { get; set; } public string bookname { get; set; } public virtual library library { get; set; } } public class library { public library() { } public int libraryid { get; set; } public virtual icollection<book> books { get; set; } }
if want use relation book side,can don't define below line in library class definition?
public virtual icollection<book> books { get; set; }
sure, can this:
modelbuilder.entity<book>() .hasrequired(b => b.library) // or: hasoptional .withmany() .map(m => m.mapkey("libraryid"))
in case, database table book
has foreign key field libraryid
that's either required or optional (nullable). foreign key not mapped property in class book
. called independent association.
you can map key property in book
if want:
modelbuilder.entity<book>() .hasrequired(b => b.library) .withmany() .hasforeignkey(b => b.libraryid))
this turns association foreign key association. in many cases can beneficial.
Comments
Post a Comment