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?
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.
And what is the point of your effort? It is mostly useless because:
virtual
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.