c# - Initialize EF(6) object with primary key through constructor (best practice?) -
i've googled heck out of day, , haven't found answer. seems such simple topic somewhere, maybe i'm searching wrong... forgive me if duplicate...
currently, in project, data-access level objects initialized method in partial class. it's created, null values across board, , call custom method on it, contains variant of:
public myobject getmyobjectbyid(int myprimarykey) { using (var db = new mycontext()) { myobject myobject = new myobject(); myobject = db.myobjects.find(myobject.primarykey = myprimarykey); return myobject; } } ...and assign myobject created initial object.
so works... seems lot of run around. if find() simple, , works smoothly off primary key, shouldn't there way put in constructor? create object
myobject myobject = new myobject(myprimarykey); like said, i've googled morning, looking constructors ef6, , constructors primary key... can't seem find i'm sure obvious answer...
the main reason not put logic in constructor because class coupled repository. keeping creating logic outside of class decouple class storage mechanism.
suppose wanted use different repository (say flat file testing). if repository access baked constructor, you'd have either have convoluted logic choose repository based on external trigger, or use different signature since can't have multiple constructors same signature.
also, think constructor like:
public myobject (int pk) { db = // repository // can't "this = ...", have create temporary object , copy. myobject temp = db.myobjects.find(myobject.primarykey = myprimarykey); // copy properties of `temp` `this` }
Comments
Post a Comment