如何将这两个实体框架查询合并为一个?

时间:2014-02-06 17:05:00

标签: asp.net-mvc entity-framework

我想将这两行结合起来:

var product = await db.Products.SingleOrDefaultAsync(p => p.SeoName == productSeoName);
var photos = await db.Photos.Where(p => p.ProductId == product.ProductId).OrderBy(p => p.Importance).ToListAsync();

在此操作方法中:

public async Task<ActionResult> Details(string productSeoName)
{

    var product = await db.Products.SingleOrDefaultAsync(p => p.SeoName == productSeoName);
    var photos = await db.Photos.Where(p => p.ProductId == product.ProductId).OrderBy(p => p.Importance).ToListAsync();



    if (product == null)
    {
        return HttpNotFound();
    }

    var addToCart = new AddToCartViewModel
    {
        ProductPhotos = photos

    };
    return View(addToCart);
}

这样的事情(伪):

    var product = await db.Products.OrderBy(p => p.ProductPhotos.Importance).SingleOrDefaultAsync(p => p.SeoName == productSeoName);

var addToCart = new AddToCartViewModel
{
    ProductPhotos = product.ProductPhotos

};

那是;我想获得一个产品并订购该产品的ProductPhotos系列,所有这些都集成在一行代码中。怎么做?

产品型号:

public class Product
{
    public int ProductId { get; set; }

    public virtual List<Photo> ProductPhotos { get; set; }
}

照片模特:

public class Photo
{
    public int PhotoId { get; set; }

    public int ProductId { get; set; }

    public virtual Product Product { get; set; }

    public int Importance { get; set; }
}

1 个答案:

答案 0 :(得分:0)

这是不可能的。照片将加入产品,您无法订购加入。我所做的是利用我的视图模型上的属性以我想要的格式返回连接的数据。如下所示:

public class ProductViewModel()
{
    ...
    public List<Photo> Photos { get; set; }

    public List<Photo> OrderedPhotos
    {
        get { return Photos.OrderBy(m => m.Importance); }
    }
}

然后:

var product = await db.Products.OrderBy(p => p.Importance).Include("Photos").SingleOrDefaultAsync(p => p.SeoName == productSeoName);

// map product to an instance of `ProductViewModel`, either manually or with something
// like AutoMapper

return View(model); // where model is your instance of `ProductViewModel`

注意上面使用Include。这告诉EF继续并选择属于该产品的所有照片,因此您不必在以后再发出该查询。

然后,在您看来,您只需使用OrderedPhotos代替Photos