Jon February 2016

Initialize EF(6) object with primary key through constructor (best practice?)

I've googled the heck out of this all day, and haven't found an answer. This seems like such a simple topic that it would be somewhere, but maybe I'm searching wrong... but forgive me if this is a duplicate...

Currently, in the project, all data-access level objects are initialized by a method in a partial class. So it's created, with null values across the board, and then we call a custom get method on it, which contains some 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 the MyObject created to the initial object.

So that works... but it seems like a lot of run around. If the find() is so simple, and works so smoothly off the primary key, shouldn't there be a way to put that in a constructor? Just create the object with

MyObject myObject = New MyObject(MyPrimaryKey);

Like I said, I've googled it all morning, looking for constructors for ef6, and constructors with primary key... can't seem to find what I'm sure is an obvious answer...

Answers


D Stanley February 2016

The main reason not to put that logic in the constructor is because then the class is coupled to the repository. By keeping creating logic outside of the class itself you decouple the class from the storage mechanism.

Suppose you wanted to use a different repository (say a flat file for testing). If your repository access was baked into your constructor, you'd have to either have convoluted logic to choose the repository based on some external trigger, or use a different signature since you can't have multiple constructors with the same signature.

Also, think about what that constructor would look like:

public MyObject (int pk)
{
   db = // get repository

   // can't say "this = ...", so we have to create a temporary object and copy.
   MyObject temp = db.MyObjects.Find(myObject.primaryKey = myPrimaryKey);

   // copy properties of `temp` to `this`
}

Post Status

Asked in February 2016
Viewed 1,970 times
Voted 13
Answered 1 times

Search




Leave an answer