2

I'm using Entity Framework to save my data to a database. Now I have a class:

public class User 
{
   public int Id { get; set; }
   public virtual ICollection<User> Friends { get; set; }
   public virtual User BestFriend { get; set; }

   public User()
   {
      Friends = new HashSet<User>();
   }
}

I load a User with

User user;
using(var context = DatabaseContext) 
{
   user = context.Users.Select(x => x.Id == 1);
}

the Friends and BestFriend property is null. This however is working:

  User user;
  using(var context = DatabaseContext) 
  {
     user = context.Users.Include(x => x.BestFriend).Include(x => x.Friends).Select(x => x.Id == 1);
  }

This leaves me with the Problem that e.g. user.BestFriend.BestFriend is null. I could include this property, too, but this would lead only to more problem a level deeper.

How know that lazy-loading and eagerly loading does exists, but I don't know how to use any of this here to my advantage.

Thanks

Florian
  • 1,677
  • 1
  • 29
  • 59
  • Have a look at this question: http://stackoverflow.com/questions/3356541/entity-framework-linq-query-include-multiple-children-entities and at this MSDN article: http://msdn.microsoft.com/en-us/data/jj574232.aspx – Eduard Dumitru Nov 23 '13 at 20:39
  • @EduardDumitru as this describes both methods good, it does not help me regarding how to avoid needing load many levels manually. – Florian Nov 23 '13 at 21:11
  • 2
    There is no magic way to do recursive querying with LINQ to a SQL backend. Nothing you can do about is. You can only allow lazy loading by extending the context's lifespan. – Gert Arnold Nov 23 '13 at 22:59
  • @GertArnold And it is good thing too, that you have to specify the levels, otherwise you could end up pulling the entire table into memory. Go figure facebook for instancen :-) – Dabblernl Nov 24 '13 at 00:06
  • @Dabblernl but can't I configure it, that it will reload it, if I access it. Like lazy loading but outside the context. – Florian Nov 24 '13 at 00:13
  • @Campl3r Well, you can always write code in the BestFriend Property's getter that checks if it is null. Or you can encapsulate the User entitiy in an other class. – Dabblernl Nov 24 '13 at 07:19

0 Answers0