Object Oriented Complex Objects with Lists

This is my first stack overflow question, so I will 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 am facing is this: 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 great:

    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 use the Framework 6 entity, MVC 5 and the first code migrations. Now I'm a little worried about performance, and I would like to know the cause of this problem and how to avoid it.

Many thanks

+3
source share
1 answer

Find Entity Framework , (, ), - Membres. , NullReferenceException .ToList() projet.Membres.

. virtual ...

public virtual List<Membre> Membres { get; set; }

..., EF " " ( ). Include projet plus Membres :

Projet projet = db.projets.Include(p => p.Membres)
    .SingleOrDefault(p => p.ID == id);
IList<Membre> SelectionList = projet.Membres;

( using System.Data.Entity; , Include .)

, , , .

.

+11

All Articles