Entities创建带有嵌套对象列表的对象

Entities创建带有嵌套对象列表的对象

本文介绍了使用LINQ to Entities创建带有嵌套对象列表的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Linq to Entity Framework创建一个包含对象列表的对象.但是我收到了NotSupported异常.我的数据库结构与LinqPad附带的数据库非常相似.让我们举个例子-我有一个customer域对象和Purchase(或者对于ex-Order)域对象.

I am trying to create an object that contains the list of objects using Linq to Entity Framework. But I am getting NotSupported exception. My db structure is very similar to the db that comes with LinqPad. Let’s take that for example – I have a customer domain object and Purchase (or for ex - Order) domain object.

Public Class Customer (){ long CustID ,string CustName , List<Purchase> purchases }
Public Class Purchase () { long PurchaseID}

我试图使用这样的导航属性在DAL中填充客户"域对象-

I am trying to populate the Customer domain object in DAL using the navigation properties like this -

db.Customer
.Where( t=> t.CustID==1)  //hard coding for 1
.Select( t=> new Customer()
{
CustName = t.name ,
Purchases = t.Customer.Purchase
        .Select ( p=> new Purchase()
            {
                PurchaseID=p.purchaseid
}).ToList()
});

我为此获得了NotSpported例外

我还尝试为purchases – GetPurchases()创建方法.它返回购买清单,并将其分配给我正在创建的客户对象.但是我仍然遇到同样的例外.我收到错误消息NotSuuported异常–

I also tried creating a method for purchases – GetPurchases(). It returns the list of purchases and assigned it to the customer object that I am creating up. But I am still getting the same exception.I am getting NotSuuported exception with error message –

.我搜索了一下,似乎它在linq to sql中受支持,但在linq to ef中却不受支持.我正在尝试做与此类似的事情-使用linq返回带有list< object>的对象.成员是否可以像我一样填充域对象.是否有任何已知的解决方案或解决方案.

. I searched and it seems like its supported in linq to sql but not in linq to ef. I am trying to do the same thing like this post - Using linq to return an object with a list<object> memberIs it possible to populate the domain object like I am doing. Are there any known solutions or work around for this.

推荐答案

以下是类似示例的有效示例.在这种情况下,将填充嵌套的Taxes集合.

Here is a working example of something similar. In this case it is the nested Taxes collection that is being populated.

public async Task<IEnumerable<ServiceLayer.DTO.Vendor>> GetAllVendors()
{
    return await (

        from vendor in _db.Vendors

        select new ServiceLayer.DTO.Vendor()
        {
            Id = vendor.Id,
            Name = vendor.Name,
            Taxes = (from tax in _db.VendorTaxes
                     where tax.VendorId.Equals(vendor.Id)
                     select new DTO.VendorTax() { Id = tax.Id, Rate = tax.Rate })
        })

    .ToListAsync();
}

这篇关于使用LINQ to Entities创建带有嵌套对象列表的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 01:50