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; }
}
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; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With