Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select specific columns from table, Entity Framework

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())?

like image 396
SᴇM Avatar asked Sep 25 '17 11:09

SᴇM


People also ask

How do I select specific columns in Entity Framework?

We can do that simply by using the “new” operator and selecting the properties from the object that we need. In this case, we only want to retrieve the Id and Title columns. There.

How do I select certain columns in a table?

Note: Pressing CTRL+SPACEBAR once selects the table column data; pressing CTRL+SPACEBAR twice selects the entire table column. Click the left border of the table row. The following selection arrow appears to indicate that clicking selects the row.

What difference does AsNoTracking () make?

AsNoTracking() allows the "unique key per record" requirement in EF to be bypassed (not mentioned explicitly by other answers). This is extremely helpful when reading a View that does not support a unique key because perhaps some fields are nullable or the nature of the view is not logically indexable.


1 Answers

    var items = context.MyTable.Where(x => x.Id == id)
                  .Select(x => new
                               {
                                    P1 = table.Prop1,
                                    P2 = table.Prop2
                               });

This will translate into a sql call like:

SELECT p.Prop1, p.Prop2 FROM mytable p WHERE p.Id = id
like image 162
thisextendsthat Avatar answered Oct 05 '22 16:10

thisextendsthat