views:

140

answers:

1

I have 2 classes: User and Booklink

     public class User
        {
            public int UserID { get; set; }
            public string Email { get; set; }
            public string Login { get; set; }
            public string Surname { get; set; }
            public string Name { get; set; }
            public int Points { get; set; }
            public string Password { get; set; }

            public IEnumerable<BookLink> BookLinks { get; set; }
        }

public class BookLink
        {
            public int LinkID { get; set; }
            public int BookID { get; set; }
            public int UserID { get; set; }
            public DateTime EventDate { get; set; }

            public Book Book { get; set; }
            public User User { get; set; }

        }

I used new EF4.0 feature - POCO.

The problem: when I load user entity BookLinks property is NULL (there are some child records in Booklinks table). But other fields(properties) was loaded fine and all of them (except Booklinks) have their values from database.

I receive objects from generic repository like this:

UsersRepository usersRepository = new UsersRepository();

            User user = usersRepository.FindByID(1);

FindByID method is implemented like this

private ObjectSet<T> _entitySet;    
return _entitySet.AsQueryable().Where(predicate).SingeOrDefault();

And navigation property Booklinks in user instance is NULL

I cant understand why I see this behaivour. How I can load child records automatically?

Here is screenshot from EF designer http://tinyurl.com/2ct45d5 (if it will help...)

A: 

Lazy loading can't work on a POCO unless you declare your association virtual (you haven't) and enable proxy creation (the default, IIRC).

Craig Stuntz
I set "ContextOptions.ProxyCreationEnabled = true;" and marked BookLinks collection as virtual - "public virtual IEnumerable<BookLink> BookLinks { get; set; }"But my problem was not solved. Booklinks propery is still NULL.
VoimiX
You must also enable LazyLoading as well. Its one of the option on the ContextOptions
zeeshanhirani
I solved my problem by this:public virtual ICollection<BookLink> BookLinks { get; set; }But I cant understand are there huge differencies between IEnumerable and ICollection?
VoimiX
That makes sense. You (and, perhaps more importantly, the EF) can't add to an IEnumerable.
Craig Stuntz