c# - 如何使用 LINQ to Entities(带转换)返回嵌套数据集?

标签 c# .net linq linq-to-entities

我正在将实体对象转换为我自己的模型(CustomerModel 和 OrderModel)。

我目前有一个返回我的客户的 IQueryable 方法:

IQueryable<CustomerModel> GetCustomers()
{
    return from c in entities.Customers
           select new CustomerModel {
               CustomerId = c.CustomerId,
               CustomerName = c.CustomerName
               // Orders = ??
           };
}

在我的 CustomerModel 中,您可以看到我有一个订单数组。

class CustomerModel {
    public int CustomerId { get; set; }
    public string CustomerName { get; set; }
    public OrderModel[] Orders { get; set; }
}

class OrderModel {
    public int OrderId { get; set; }
    public int CustomerId { get; set; }
    public string OrderDetails { get; set; }
}

当 Orders 类型为 Array 时,我似乎无法弄清楚如何在 Customer 对象中设置 Orders。

当我将 CustomerModel 的订单更改为 IEnumerable 而不是数组时,我能够做到这一点,并且您不能将 .ToArray() 与 LINQ to Entities 一起使用,所以我被卡住了。

所以我的问题是:使用数组来处理订单是否可行?

问题的答案:

  • 为什么是数组?我在其他地方返回一个数组(供其他项目使用),让订单也成为一个数组是有意义的。

此外,您不能对订单使用 ToArray(),会抛出此错误:

System.NotSupportedException: LINQ to Entities does not recognize the method 'Proj.Models.Orders[] ToArray[Orders](System.Collections.Generic.IEnumerable`1[Proj.Models.Orders])' method, and this method cannot be translated into a store expression.

最佳答案

如果您的 Orders可从 Customers 访问,你可以试试:

IQueryable<CustomerModel> GetCustomers()
{
    return from c in entities.Customers
           select new CustomerModel {
               CustomerId = c.CustomerId,
               CustomerName = c.CustomerName
               Orders = from o in c.Orders
                        select new Order{
                            OrderId = o.OrderId,
                            ...
                        }
           };
}

这需要您更改 Customer.OrdersIEnumerable<Order> .这是在对数据库的一次请求中加载对象图的唯一方法。

关于c# - 如何使用 LINQ to Entities(带转换)返回嵌套数据集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8828705/

相关文章:

c# - 使用 LINQ 查找与条件匹配的元素的第一个索引

c# - 将多个 csv 文件作为单个数据集加载的最佳方法

.NET 串行端口多线程

.net - 使用 OpenGL 直接绘制到 .NET 位图

linq - 在Linq中返回单个列表属性List

asp.net - Linq to Entities 查询结果的基础类型是什么?

linq - 删除无查询的Azure表中的通配符行

c# - 动态命令行参数和预加载任务,同时保持调试

c# - 解析 IContainer

.net - 检查 WCF 连接