this is my first question on stack overflow so i'll try to be precise. This is my model :
namespace GRHMeca.Models
{
public class Projet
{
[Key]
public int ID { get; set; }
[Required]
public String Nom { get; set; }
public String Description { get; set; }
public List<Membre> Membres { get; set; }
}
}
and Membre is another regular model.
The problem I'm facing is the following : if I do this:
Projet projet = db.projets.Find(id);
IList<Membre> SelectionList = projet.Membres.ToList();
I get a null pointer exception; But this works fine:
IEnumerable<Membre> SelectionList = new List<Membre>();
SelectionList = db.Membres
.ToList()
.AsEnumerable<Membre>()
.Except<Membre>(
db.Membres
.ToList()
.AsEnumerable<Membre>()
.Except<Membre>(
projet.Membres
.ToList()
.AsEnumerable<Membre>()
)
)
.ToList();
I'm using entity Framework 6, MVC 5, and code first migrations. Now I'm a little worried about performance, and I would like to know the reason of this problem and how to avoid it.
Many Thanks
When you call Find Entity Framework loads an entity from the database but without loading its navigation properties (the properties that refer to other entities) - like the Membres collection. Because it isn't loaded nor initialized to an empty collection you get a NullReferenceException when you call .ToList() on projet.Membres.
You have two options here. Either add the virtual keyword to the collection...
public virtual List<Membre> Membres { get; set; }
...which will enable EF to "lazily load" the collection when you access it (which is a second database query). Or use the Include method to load projet plus Membres collection in a single query:
Projet projet = db.projets.Include(p => p.Membres)
.SingleOrDefault(p => p.ID == id);
IList<Membre> SelectionList = projet.Membres;
(Add using System.Data.Entity; to your code file to have the Include method with lambda expression available.)
I'd prefer the second option in your case because you know up front that you want to load both parent entity and child collection.
You can read more about loading related entities here.
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