EF 4.1 - Add items to collection property that is virtual
I'm using EF 4.1 code first. Given the following class snippet:
public class Doctor
{
public virtual ICollection<Hospital> Hospitals { get; set; }
}
Note: I have this in the database context:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
this.Configuration.LazyLoadingEnabled = false;
}
I wanted to make sure that lazy loading is not involved here.
The issue I have is that, without the virtual
keyword on the Hospitals property, when I retrieve a doctor that does have a hospital associated with him, the collection is empty.
By including the virtual
keyword, the hospitals collection does contain 1 item, which is what I expect.
The problem is that, when I want to create a brand new doctor and associate him with a hospital immediately, I get a Null reference
exception, since the Hospitals property has not been initialised yet.
Can someone point out what I'm doing wrong here? How can I开发者_如何学C add items to the Hospitals upon creating a new doctor.
Cheers. Jas.
Your code is something what you usually see in all examples but to make this work this one is much better:
public class Doctor
{
private ICollection<Hospital> _hospitals;
public virtual ICollection<Hospital> Hospitals
{
get { return _hospitals ?? (_hospitals = new HashSet<Hospital>()); }
set { _hospitals = value }
}
}
If you don't use virtual
keyword EF will not initialize collection for you. In the same time if you create brand new Doctor
via its constructor you must handle initialization yourselves.
I think this can help you.
public class Doctor
{
public Doctor()
{
Hospitals = new ICollection<Hospital>();
}
public virtual ICollection<Hospital> Hospitals { get; set; }
}
精彩评论