none
Returning all records? RRS feed

  • Question

  • Hi all,

    Using EF4 POCO & ObjectContext, I have a class:

    public partial class CustomerType : BaseDataObject<CustomerType>
    {
    
            public static CustomerType Load(int ID)
            {
                return CustomerType.context.CustomerTypes.Where(o => o.ID == ID).AsEnumerable().FirstOrDefault();
            }
    
    }

    If I understand correctly, the above code should return just 1 record in the context. However, when I do

    context.CustomerTypes.ToList().Count;

    I get 14, which is the number of records in the database.

    Am I missing something here?

    Ivan


    • Edited by Cryo75 Wednesday, May 30, 2012 7:57 AM
    Wednesday, May 30, 2012 7:57 AM

Answers

  • No it doesn't contain anything, it just *represents* the set of entities. Basically this is just a SELECT * query that you can enrich before runing it (when enumerating the content).

    If you want to keep materialized entitie(s), you have to assign ToList to your own collection (the DbContext API has a Local property that allows to retrieve previously loaded entities) or Load() to an entity variable.


    Please always mark whatever response solved your issue so that the thread is properly marked as "Answered".

    Wednesday, May 30, 2012 10:04 AM

All replies

  • Hi,

    It seems you think that those two snippets are related in some way ? context.CustomerTypes exposes the whole collection and performs a query when its content is enumerated so the first snippet returns a single entity while the other returns all entities available in the db. They are just two distinct unrelated queries... What makes you think the second one should return only a single entity ?


    Please always mark whatever response solved your issue so that the thread is properly marked as "Answered".


    Wednesday, May 30, 2012 9:20 AM
  • Ah ok. So if I don't enumerate, does the CustomerTypes contain just the 1 record that I fetched during the lifetime of the context?
    Wednesday, May 30, 2012 9:23 AM
  • No it doesn't contain anything, it just *represents* the set of entities. Basically this is just a SELECT * query that you can enrich before runing it (when enumerating the content).

    If you want to keep materialized entitie(s), you have to assign ToList to your own collection (the DbContext API has a Local property that allows to retrieve previously loaded entities) or Load() to an entity variable.


    Please always mark whatever response solved your issue so that the thread is properly marked as "Answered".

    Wednesday, May 30, 2012 10:04 AM
  • use Select or All  in conjunction with Where

    Mark Answered, if it solves your question
    Rohit Arora

    Wednesday, May 30, 2012 10:33 AM