c# - when is it mandatory to use fluent api when defining relationships -
i wonder if ever mandatory use fluent api when defining 1:m, 1:1, , m:m relationships. know fluent api provides more functionality data annotations not able do. however, if think straight relationships no additional requirement (e.g., renaming foreign keys in m:m relationships, or cascadeondelete, etc.), can rely on data annotations ? or still better use fluent api reasons?
everything can dataannotation
can fluentapi
, opposite not true. features available in fluentapi
.
which should use?
depending on trying do.
some relationships can declared in class structure. instance, n:m relationship can declared follows:
public class foo { public icollection<bar> bars { get; set; } } public class bar { public icollection<foo> foos { get; set; } }
ef recognize n:m: relationship , create "third table". however, if want "choose" third-table's name, have use fluentapi
.
modelbuilder.entity<foo>() .hasmany(s => s.bars) .withmany(c => c.foos) .map(cs => { cs.mapleftkey("fooid"); cs.maprightkey("barid"); cs.totable("foobarrelationship"); });
dataannotation
more simple fluentapi
, if classes located in different assembly, have add reference of system.data.componentmodel
, not nice.
fluentapi
seems complicated, can dataannotation
can do, , more. in addition, can use outside of class without problems. particularly, prefer fluentapi
, because seems more clean , organised.
futhermore, if choose dataannotation
, keep in mind might have use fluentapi
well. so, if want use 1 approach, must choose fluentapi
.
Comments
Post a Comment