简体   繁体   English

如何在实体框架中获取一些实体列?

[英]How to get some columns of entity in entity-framework?

Assume I have a table with more than 1000000 columns. 假设我有一个超过1000000列的表。 When I use LINQ To SQL and Entity-Framework all queries will write in c# like below: 当我使用LINQ To SQLEntity-Framework所有查询都将在c#中编写,如下所示:

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? 有没有办法只获得1000000列中的第1列和第2列和第3列?

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. 结果数据的类型应该在选择后保留,例如,如果没有过滤某些列类型的结果是Type1,那么非常重要的是,在过滤之后,结果的类型是Type1,但是过滤的Type1的那些属性的值应该是null或default。

To only get a few ROWS you can use: 要获得一些ROWS,您可以使用:

.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(). 请注意,该对象现在未附加到objectcontext,因此它不会受到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. 我知道你在Entity Framework中获得列的一个子集的唯一方法是创建一个新的实体类,它只有你感兴趣的列并将它映射到同一个表。 EF will then not select those columns when querying against that entity. 在查询该实体时,EF将不会选择这些列。 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). 根据数据库定义,子集实体可能完全不足以插入或更新行而不违反约束,但它可以是一个非常有用的工具,可以减少您对选择所做的不必要的数据传输量,以及实现具有许多不需要的列的实体的时间损失(这可能非常重要)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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