LINQ to Entities Retrieving related Entities or T-SQL

时间:2015-06-15 17:56:00

标签: c# sql-server linq

I have these (simplified) models:

class Vendor
{
    public int Id { get; set; }
    public IEnumerable<Product> Products { get; set; }
    public IEnumerable<Booth> Booths { get; set; }
}

class Show
{
    public int Id { get; set; }
    public IEnumerable<Booth> Booths { get; set; }
}

class Booth
{
    public int VendorId { get; set; }
    public Vendor Vendor { get; set; }

    public int ShowId { get; set; }
    public Show Show { get; set; }
}

class Product
{
    public int Id { get; set; }
    public int VendorId { get; set; }
    public IEnumerable<ProductPic> Pics { get; set; }
}

class ProductPic
{
    public int Id { get; set; }
    public int ProductId { get; set; }
    public string Uri { get; set; }
}

I don't care if I use LINQ or

IEnumerable<Vendor> vendorsWithProductsAndPicsInShow = db_.Vendors.SqlQuery(sql).AsEnumerable();

I just want the result to be a list of vendors, along with their products and productPics in a particular show.

I'm trying to go about it by querying the booths, something like

Vendor[] vendorsInShow = (from b in db_.Booths
                        .Include(m => m.Vendor)
                        .Include(m => m.Vendor.Products)
                        .Where(m => m.ShowId == showId && m.Vendor.Products.Count > 0)
                            select b.Vendor).AsNoTracking().ToArray();

but that query doesn't end up including the products, and I still need to retrieve the ProductPics for each Product.

What do I need to do here?

1 个答案:

答案 0 :(得分:1)

您可以尝试从供应商中选择并使用Any()来显示ShowId。

Vendor[] vendorsInShow = (from v in db_.Vendor
      .Include("Products.Pics")
      .Where(m => m.Booths.Any(a => a.ShowID == showId) 
           && m.Products.Count > 0)
   select v).AsNoTracking().ToArray();