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

亡梦爱人 提交于 2019-12-10 21:24:17

问题


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.


回答1:


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.




回答2:


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).



来源:https://stackoverflow.com/questions/22324064/how-to-get-some-columns-of-entity-in-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!