Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid calling virtual function in constructor?

Most (if not all) my Entity Framework POCOs have virtual functions. I need these functions to be virtual so that the entities can be lazy-loaded.

If I initialize Accommodations in constructor then I will be calling a virtual function in constructor, which is bad practice.

But how can I initialize Accommodations if not in the constructor?

public class Venue
{
    public Venue()
    {
        Accommodations = new HashSet<Accommodation>();
    }

    public virtual ICollection<Accommodation> Accommodations { get; set; }
}
like image 911
Rosdi Kasim Avatar asked Apr 17 '13 08:04

Rosdi Kasim


1 Answers

Another option is to mark the setter as private. This will do away with the issue of calling virtual members in constructor.

Once you do that, you need to provide ways for callers (other than EF) to set that property as needed by your design. You can use an overloaded constructor to pass in a list of accommodations, or optionally encapsulate your collection (Domain driven design) and use methods to add/remove items (note, with EF this becomes "hackish", as it lacks support for fully encapsulated collections, unlike with NHibernate):

public class Venue
{
    public Venue()
    {
        Accommodations = new HashSet<Accommodation>();
    }

    public Venue(ICollection<Accommodation> accommodations)
    {
        Accommodations = new List<Accommodation>(accommodations);
    }

    public virtual ICollection<Accommodation> Accommodations { get; private set; }
}
like image 66
Thiago Silva Avatar answered Nov 04 '22 11:11

Thiago Silva