开发者

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 Init开发者_如何学Pythonializer).

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.


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.


The virtual properties are populated once the entity is attached and saved to the context or returned by the context.

If you really want Category to not be null you should set the id (or navigation property) and apply the changes to the context.


If they're POCOs, expose the CategoryId as a readonly property:

public class Note
{
    public int Id { get; set; }
    public int? CategoryId { get { return Category == null ? (int?)null : Category.Id; } }
    public virtual Category Category { get; set; }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜