开发者

Mixing local list operations with linq to entities database operations

I have 2 lists. A shopping cart list, which contains a objects with the properties; Quantity and ProductId. I then get all products from the repository (IQueryable) that has ProductId in the shopping cart list. This means that for every product, there is a shopping cart object with the Quantity related to it.

When doing the select, I want to assign this Quantity also, but the only way I know to do this is to query the cart again.

For egx.

        model = (from p in productService.GetAllProducts()
                              where cart.Entries.Select(c => c.ProductId).Contains(p.ProductId)
                              select new CartViewItem
                                         {
                                             Price = p.Price,
                                             ProductId = p.ProductId,
                                             ProductName = p.ProductName,
                                             Quantity = cart.Entries.FirstOrDefault(c => c.ProductId == p.ProductId).Quantity
                                         }).ToList();

Model:

public class ShoppingCartEntry
{
    public int ProductId { get; set; }
    public int Quantity { get; set; }
}

cart.Entries is not coming from a repository. productService.GetAllProducts() returns an entityframework's IQueryable.

EDIT: My new code is:

        model= (from p in productService.GetAllProducts()
                              from c in cart.Entries
                              where c.ProductId == p.ProductId
                              select new CartViewItem
                                         {
                                             Price = p.Price,
                                             ProductId = p.ProductId,
                                             ProductName = p.ProductName,
                                             Quantity = c.Quantity
                                         }).ToList();

This throws an error: Unable to create 开发者_开发知识库a constant value of type 'SampleApp.WebUI.Models.ShoppingCartEntry'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.


i think this should work...

var model = (from c in cart.Entires  // The small local cart collection
             let cpid = cart.Entires.Select(c2 => c2.ProjectId) // 
             from p in productService.GetAllProducts() // Query all Products used in cart
                               .Where(queryp => cpid.Contains(queryp.ProjectId)).ToList()
             where p.ProductId == c.ProductId
             select new CartViewItem {
                 p.Price,
                 p.ProductId,
                 p.Brand,
                 p.ProductName,
                 Discount = p.DiscountPercent * c.Quantity}).ToList();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜