views:

839

answers:

5

If I use entity framework with linq to sql to query it and I have an object Person but I only need two properties of that object, what's in memory will be load, the entire object ?

Example :

I got the entity Person with properties : Name, Age, Address, Country, Language ...

I only need to use the property Name and Age. So I got no need to load the address, country and other property ... what will be in memory and what type of query will be ask to SQL ?

If my Linq query is :

public IQueryable<Person> FindAllPersons()
{
    return from person in db.Persons
           select person;
}

And later in code I only call the Name and Age property of each Person in the list.

+4  A: 

You can query for only the fields you need.

Like so,

public IQueryable<Person> FindAllPersons()
{
    return from person in db.Persons
           select new Person(){Name = person.Name, Age = person.Age};
}
Jeremy
I tried it and I get the following NotSupportedException: "The entity or complex type 'CompleteKitchenModel.Contact' cannot be constructed in a LINQ to Entities query."I posted a question here: http://stackoverflow.com/questions/2011100/loading-partial-entities-with-linq-to-entities
Shimmy
+2  A: 

If you select the entire person object with LINQ, then when you access that object, the entire person will be loaded into memory. If you wish to select only specific fields, you should refine your selection criteria. For example:

var persons = from p in db.Persons select new { p.Name, p.Age };
Scott Anderson
+1  A: 

Although this isn't absolutely necessary you may want to specify whether you are using the EF or Linq2SQL. However depending on which one you are actually using the SQL could potentially be different.

From the query you specified all of the properties that are tied to a database column will be filled on the object (as long as they aren't Entity References). You could probably effectively use delay loading on the other properties but that isn't a blanket solution and will probably be counter productive in a different area of your application. All in all I would say unless the application has to be extremely memory sensitive just load the objects as they are.

To load just name and age..

var list = db.Persons.Select(person => new Person() { Age = person.Age, Name = person.Name });
Quintin Robinson
+3  A: 

As an alternative, you can set Delay Loaded to true for all columns you don't want to be loaded instantly.

Devart
Can you give me an example or a link to that option please ?
Melursus
+1  A: 

Each entity column in the designer has the Delay Loaded property. Setting it to true (the defaut value is false) disables instant loading of the property, it will be loaded only when it is accessed in the code.