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

标签 c# linq-to-entities entity-framework-4 projection

如果我有如下类:

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/

相关文章:

c# - 如何使用 LINQ 查找和删除集合中的重复对象?

c# - 获取虚拟目录的名称?

c# - LINQ to Entities 删除异常

c# - EF4 中的日期差异

c# - webclient 窃听或什么?

C# 覆盖公共(public)成员并将其设为私有(private)

c# - 编写扩展方法来帮助查询多对多关系

c# - 通过 ADO.NET Entity Framework 使用静态数据访问方法

linq - EF4 LINQ Include(string) 替代硬编码字符串?

asp.net - 如何从 Entity Framework 中的上下文中取消附加实体?