locked
linq queries with entity framework doesn't work RRS feed

  • Question

  • I have two entity classes like order and order detail

    but when getting order object and using the orderdetails property, orderdetails property return no sequence exception

     

    I don't know why of course there are detail records in the database but why's that ????

     

     

    Wednesday, October 27, 2010 12:56 PM

Answers

  • It sounds like you need some code like this.

    if(!Item.ItemDetails.IsLoaded)

    Item.ItemDetails.Load();

    var detail = Item.ItemDetails.First();

    Note: Code may not be 100% correct as I wrote it without using visual studio.

    Let me know if this helps.

    Wednesday, October 27, 2010 2:55 PM

All replies

  • good you give more detail. Like the query itself?
    Wednesday, October 27, 2010 1:05 PM
  • of course I will I'm sorry I didn't give at first you see the reason now it is so clear code even though nothing I got .

    my code look exactly like this :

    var Item = repository.GetItem(id);

    var detail = Item.ItemDetails.First(); // I want to get the first Item Detail Only .

    ----

    Exception : ItemDetails has no sequence ;

    Wednesday, October 27, 2010 1:10 PM
  • Because you did not load ItemDetails explicitly.

    Assuming you are using 3.5SP1 because EF4 uses lazy loading by default:
    http://msdn.microsoft.com/en-us/library/bb896249%28v=VS.90%29.aspx
    http://msdn.microsoft.com/en-us/library/bb738449(v=VS.90).aspx


    /\/\arkus.
    Wednesday, October 27, 2010 2:01 PM
  • It sounds like you need some code like this.

    if(!Item.ItemDetails.IsLoaded)

    Item.ItemDetails.Load();

    var detail = Item.ItemDetails.First();

    Note: Code may not be 100% correct as I wrote it without using visual studio.

    Let me know if this helps.

    Wednesday, October 27, 2010 2:55 PM
  • Thank you so much

    Mercy

    Shokran

    ;)

    this worked like a charm , Maybe it is easy point but for me this is the first Time I use Entity Framework I thought it works like

    LinqToSql . In LinqToSql I don't need to Load() the details collection , do you ?

     

     

    Thursday, October 28, 2010 7:51 AM
  • > In LinqToSql I don't need to Load() the details collection , do you ?

    Linq2Sql always uses lazy loading, EF1 (which comes with .net 3.5) always uses eager+explicit loading.
    EF4 by default uses lazy loading but can be configured to use eager loading as well -- and also does this for models created with EF1 (and can be changed to lazy-loading then).

    http://msdn.microsoft.com/en-us/library/bb896272.aspx


    /\/\arkus.
    Thursday, October 28, 2010 8:06 AM
  • Ok I got it thanks I lot

    that's why I faced the same issue with other property which is not collection I mean like this

     

    Item item = from ....... SingleOrDefault();

     

    string name = item.Parent.Name; // this cause exception

     

    Thursday, October 28, 2010 8:37 AM