实体框架 4:如何编码投影到类类型?
如果我有一个如下所示的类:
public class Customer {
public int id {get;set;}
public string name {get;set;}
public string line1 {get;set;}
public string line2 {get;set;}
public string line3 {get;set;}
public string line4 {get;set;}
}
我只想选择 ID 和 Name 值,其余为空。
var myCustomerList = DC.Customer.Select(
p => new Customer { id = p.id, name = p.name });
我收到以下错误:
The entity or complex type 'MyModel.Customer' cannot
be constructed in a LINQ to Entities query.
您还能怎么做?我需要指定所有类的字段吗?
If I have a class like the following:
public class Customer {
public int id {get;set;}
public string name {get;set;}
public string line1 {get;set;}
public string line2 {get;set;}
public string line3 {get;set;}
public string line4 {get;set;}
}
And I only want to select the ID and Name values, leaving the rest null.
var myCustomerList = DC.Customer.Select(
p => new Customer { id = p.id, name = p.name });
I get the following error:
The entity or complex type 'MyModel.Customer' cannot
be constructed in a LINQ to Entities query.
How else would you do it? Am I required to specify all the Class's fields?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个:
上面的代码将创建一个匿名类型。
实际应用:
"var myCustomerList" <-- 匿名类型。
具有两个属性“id”和“name”的匿名类型。此外,“var”允许您创建隐式类型的局部变量。这意味着:
a) 您不必声明/编写类结构来保存仅具有这两个属性的类型;
b)您也不必维护这一点 - 您可以更改上述查询的结构,并且“它就可以了”。
Try this:
The above will create an Anonymous Type.
Practical Application:
"var myCustomerList" <-- Anonymous Type.
An anonymous type with two properties "id" and "name". Also, "var" lets you create an Implicitly typed local variable. This means:
a) You didn't have to declare/write a class structure to hold a type with only those two properties;
b) You don't have to maintain that either - you can change the structure of the above query, and "it just works".
另一种选择是创建 CustomerInfo 类型:
您无法将两种类型直接映射到 EF 中的同一个表,但您可以轻松地为您的信息类型创建一个视图,然后映射到该视图:
然后将 CustomerInfo 类型映射到您的视图:
这样做的副作用是 EF 在查询数据库时只会检索视图中的列。当通过 id 检索 CustomerInfo 时,您将得到如下 SQL:
此外,只要您的视图可更新,您就可以从 EF 更新 CustomerInfo 类型,并且基础表也将更新。
Another option is to create a CustomerInfo type:
You can't map two types directly to the same table in EF but you can easily create a view for your info type and then map to that:
You then map your CustomerInfo type to your view:
A side-effect of this is that EF will only retrieve the columns in the view when querying your database. When retrieving a CustomerInfo by id you'll get SQL like this:
In addition, as long as your view is updatable you can update your CustomerInfo type from EF and the underlying table will be updated.