简体   繁体   中英

How to get some columns of entity in entity-framework?

Assume I have a table with more than 1000000 columns. When I use LINQ To SQL and Entity-Framework all queries will write in c# like below:

EFContext.MyTableName.Where(row=>row.column1==someValue)
                     .Select(...)
                     .FirstOrDefault(...)
                     .Any(...)
                     ...

How to get only and only some columns of entity? Are there any way to get only columns 1 & 2 & 3 among 1000000 columns for example?

Attention:

Type of resulted data should keep after selection, for example if without filtering some columns type of result is Type1 it's very important that after filtering, type of result be Type1 but value of those properties of Type1 which are filtered should be null or default.

To only get a few ROWS you can use:

.Take(3);

To get only some columns you could use:

.Select(x => new MyType() { Column1 = x.Column1, Column2 = x.Column2 })

Note that the object now isn't attached to the objectcontext so it won't be affected by SaveChanges(). But you'll only have selected a few columns and the type will still be correct.

To get your own defaults instead of the framework defaults for variable types, you could modify your constructors type to set the defaults.

The only way I know of you get a subset of columns in Entity Framework is to create a new entity class which only has the columns you're interested in and map it to the same table. EF will then not select those columns when querying against that entity. You can also continue to use the full entity when you need it - nothing says you can't have two entity classes mapping to the same table. Or three. Or four...

Depending on the database definition, the subset entity may be entirely insufficient for inserting or updating rows without violating constraints, but it can be a very helpful tool to cut down on the amount of unnecessary data transfer you're doing with your selects, and the time penalty in materialising entities with lots of columns you don't need (which can be very significant).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM