Search code examples
c#entity-frameworkconstructorpoco

Initializing a POCO Entity using a constructor


I have 2 POCO classes:

(extract of them):

public class Note
{
    public int Id { get; set; }
    public int CategoryId { get; set; }

    public virtual Category Category { get; set; }

    public Note(int categoryId)
    {
    }
}

public class Category
{
    public int Id { get; set; }

    public virtual ICollection<Note> Notes { get; set; }
}

It's a 1:n relationship, Note has one Category and every category has many Notes.

I want a constructor on every Entity to initialize all the properties (it's better than using the Object Initializer).

But if I use a constructor on Note, I don't know how to "bind" the Note with its category.

If I pass the CategoryId to the constructor, Category will be null. If I pass the Category and assign the ID manually, Category will be null.

So, is there a way I can initialize a Entity using a constructor and get the category linked to my note aswell?

EDIT

As you see, I have a constructor on the Note class. My question is: Do I have to pass the categoryId, a whole Category item? (ReSharper cries if I asign something to a virtual property).

If I pass the categoryId to the object, the entities will not be linked.


Solution

  • And what is the point of your effort? It is mostly useless because:

    • You still have to provide parameter less constructor because EF needs it
    • Your custom constructor will never be used by EF
    • If you want to use lazy loading EF needs navigation properties virtual
    • It is wrong to assign virtual properties from constructor because the virtual code can be overriden in derived class and your constructor can trigger execution of logic in that derived class which hasn't been yet initialized (parent constructor executes first). It is not problem in your exact case but anybody can derive your class and override the Category property and it will become a problem. It is simply wrong practice.

    Initializers are solution for all your problems so why to bother with parametrized constructor? You should define your priorities. If lazy loading is a must for you, give up with parametrized constructor or live with the fact that Category must be configured outside the constructor. If lazy loading is not needed simply remove virtual keyword from Category and use parametrized constructor as you want.