Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy loading does not work in entity framework 5

I have defined a (poco?) class in my domain project:

public class Club
{
   public Club()
   {
      ContactPersons = new HashSet<ContactPerson>();
   }

   public int Id { get; set; }

   [Required]
   [StringLength(64)]
   public string Name { get; set; }

   public virtual ICollection<ContactPerson> ContactPersons { get; set; }
}

public class ContactPerson
{
     public virtual int Id { get; set; }

     [StringLength(64)]
     public virtual string FirstName { get; set; }

     [StringLength(64)]
     public virtual string LastName { get; set; }
 }

In my MVC project I have my clubcontroller:

   public ActionResult Create(CreateClubViewModel model)
   {
      Club club = new Club();
      model.Initialize(club);
      IClubDb clubDb = DependencyResolverHelper.IClubDbService;
      clubDb.Create(club);  // create club in db
   }

    public ActionResult Display(string domain)
    {
        try
        {
            IClubDb clubDb = DependencyResolverHelper.IClubDbService;
            Club club = clubDb.Get(domain);
            return View(club);
        }
        catch (Exception)  // user is not logged iin
        {
            return View();
        }
    }

Finally, in my DB project I create and retrieve the club,

public Club Get(string name)
{
   return DataContext.Clubs
   //.Include(x => x.ContactPersons)
   .Single(r => r.Name == name);
}

 public int Create(Club club)
 {
         DataContext.Clubs.Add(club);
         return DataContext.SaveChanges();
 }

I have tried everything to get EF to lazy load the ContactPersons of my club object when I call the Get club in the Display method but ContactPersons has always a length of zero. However, if I eager load contact persons using the .include (I have commented this part out), then obviously ContactPersons contains a number of contacts.

I am not sure what I am doing wrong:

  1. I have followed the guidelines for defining poco classes: http://msdn.microsoft.com/en-us/library/dd468057.aspx
  2. I have a public parameter less constructor (but not protected constructor)
  3. I have lazyloading enabled

I think I am missing a concept, the poco club class is also my domain entity which I insert into DB. What am I doing wrong? Whay I can't get lazy loading to work?

like image 851
user1780105 Avatar asked Nov 13 '22 14:11

user1780105


1 Answers

try ContactPersons.ToList();

this will force all entities to be loaded. see Entity framework, when call ToList() it will load FK objects automatically?

like image 94
Bassam Alugili Avatar answered Nov 15 '22 12:11

Bassam Alugili