Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity - Linq to Sql Only load a part of the entity

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.

like image 502
Melursus Avatar asked Dec 08 '25 12:12

Melursus


2 Answers

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

like image 196
Devart Avatar answered Dec 10 '25 01:12

Devart


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};
}
like image 20
Jeremy Avatar answered Dec 10 '25 00:12

Jeremy