I have a question about selecting specific columns from table using entity framework. The problem is, that I'm using Find()
method to get my desired table, by primary key, then taking from it some data.
I have one table with massive amounts of columns and if I call Find()
method, it will return all columns of that row, but I want to use only, for example, the data from 2 columns.
MyTable table = context.MyTable.Find(id); //Get MyTable object from context, id = primary key
string p1 = table.Prop1;
string p2 = table.Prop2;
This will return single object with all (for example it has Prop1, Prop2,...,PropN) properties filled (if its filled in database).
So I know that I can use anonymous objects or data transfer objects (DTO), but [question1] is there any other (yet simple) method to get specific columns? [question2] Is it affecting on performance if I use Find()
(or I should use Where()/Select()
)?
Find
and let sayFirstOrDefault(condition)
is that the former first looks at the local cache and executes db query only if the object is not there. But since it (as any method which returns entity instances) will only return fully populated objects, it cannot be used for projection (Select
) which is the only way to get partial data in EF.Find
s in my code toWhere/Select
(cause of performance issue),Find
generates for example about 300 lines ofSelect
code, butWhere/Select
about 10.Find
and the only option isWhere
+Select
.