我有以下课程:

public class Seller : Entity
{
    public int SellerId { get; set; }
    public string Name { get; set; }

    public ICollection<InventoryItem> InventoryItems { get; set; }
}

public class InventoryItem : Entity
{
    public int InventoryId { get; set; }
    public int SellerId { get; set; }
    public string SellerSku { get; set; }

    public ICollection<SiteInventoryItem> SiteInventoryItems { get; set; }
}

public class SiteInventoryItem : Entity
{
    public int Id { get; set; }
    public int InventoryId { get; set; }
    public SiteType Site { get; set; }
}


因此,Seller具有InventoryItem的集合,而该集合又具有SiteInventoryItem的集合。

如何获得带有Seller列表且带有InventoryItems列表的SiteInventoryItems,其中SiteType == SiteType.SiteNameSeller.SellerId == 14

SiteTypeEnum,数据库类型是int

我尝试了以下内容,并且可以编译并运行,但是结果不是预期的:

var seller = repo.Query(
                x => x.InventoryItems,
                x => x.InventoryItems.Select(y => y.SiteInventoryItems)
            ).Select(x => new
            {
                Seller = x,
                InventoryItems = x.InventoryItems,
                SiteInventoryItems = x.InventoryItems.Select(y => new
                {
                    InventoryItem = y,
                    SiteInventoryItems = y.SiteInventoryItems.Where(z => z.Site == SiteType.Amazon)
                })
            }).Where(x => x.Seller.SellerId == 14).First();

最佳答案

var seller = repo.Query()
        .Select(x => new
        {
            Seller = x,
            InventoryItems = x.InventoryItems.Select(y => new
            {
                InventoryItem = y,
                SiteInventoryItems = y.SiteInventoryItems.Where(z => z.Site == SiteType.Amazon)
            }).Where(y => y.SiteInventoryItems.Any())
        }).Where(x => x.Seller.Id == 14).First();


我对结果类型进行了一些重组,因为我认为这样更有意义。现在您看到结果仅返回具有SellerInventoryItemsSiteInventoryItems

请注意,我还删除了repo.Query()的参数。我假设它们充当Include。但我也希望repo.Query()返回一个IQueryable,以便将Where子句转换为生成的SQL。如果是这样的话,Include是无用的,因为您已经在查询包含的实体,因为它们是匿名类型的一部分。

关于c# - Entity Framework 选择查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32079315/

10-11 17:52