Lazy loading does not work in entity framework 5

asp.net-mvc entity-framework lazy-loading

Question

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?

1
5
1/1/2013 9:49:36 PM

Popular Answer

try ContactPersons.ToList();

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

1
5/23/2017 11:53:55 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow