I'm using EF4.3. It's my first project so I'm learning as I go along.
There are instances where I need to implment additional constructors for entities. I create an additional partial class to do this, so entity Users, will have an associated class User2.
I've noticed that EF on the whole doesn't create constructors, but there are instances like this:
public partial class User
{
public User()
{
this.BookmarkedDeals = new HashSet<BookmarkedDeal>();
this.BookmarkedStores = new HashSet<BookmarkedStore>();
}
public System.Guid UserId { get; set; }
public int UserStatusId { get; set; }
public int UserRoleId { get; set; }
public System.DateTime CreatedOn { get; set; }
public System.DateTime LastVisitedOn { get; set; }
public virtual ICollection<BookmarkedDeal> BookmarkedDeals { get; set; }
public virtual ICollection<BookmarkedStore> BookmarkedStores { get; set; }
public virtual Subscriber Subscriber { get; set; }
}
This got me worrying a little because its so easy to add a navigation property via the designer, and code within the base constructor missed.
public User()
{
this.BookmarkedDeals = new HashSet<BookmarkedDeal>();
this.BookmarkedStores = new HashSet<BookmarkedStore>();
}
My question is, do I need to call the base constructor from my additional contructors and should I put the code (: this User()) to call my base constructor in all cases as a safeguard?
EF (Database First or Model First) creates those default constructors...
public User()
{
this.BookmarkedDeals = new HashSet<BookmarkedDeal>();
this.BookmarkedStores = new HashSet<BookmarkedStore>();
}
...only as a helper to instantiate the navigation collections to guard you a little bit against NullReferenceException
s. But it is not required. If you load a User
entity from the DB including the BookmarkedDeals
and BookmarkedStores
EF will instantiate the collections anyway. If you create a User
yourself you just had to instantiate the sets manually if the constructur wouldn't be there:
var user = new User { BookmarkedDeals = new HashSet<BookmarkedDeal>() };
user.BookmarkedDeals.Add(new BookmarkedDeal());
If you add a new constructor I would call the default constructor to have the instantiation of the collections consistent between all constructors. But I think it must be this
, not base
because both constructors are in the same class, not in an inheritance hierarchy:
public User(SomeType SomeParameter) : this()
{
//Do somthing with SomeParameter...
}