gpt4 book ai didi

c# - Entity Framework 4 : How to code projection to a class type?

转载 作者:行者123 更新时间:2023-11-30 12:36:04 26 4
gpt4 key购买 nike

如果我有如下类:

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.

否则你会怎么做?我是否需要指定类的所有字段?

最佳答案

试试这个:

var myCustomerList = from c in DC.Customer 
select new { id = p.id, name = p.name };

以上将创建一个 Anonymous Type .

实际应用:

"var myCustomerList"<-- 匿名类型。

具有两个属性“id”和“name”的匿名类型。此外,“var”允许您创建隐式类型的局部变量。这意味着:

a) 您不必声明/编写类结构来保存仅具有这两个属性的类型;

b) 您也不必维护它 - 您可以更改上述查询的结构,然后“它就可以工作”。

关于c# - Entity Framework 4 : How to code projection to a class type?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4006769/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com