Reputation: 693
I'm currently building a web shop for a school project where I'm storing the ID to my model and a desired count in my Cart-object (in Session). When the customer wanna look at their shopping cart I need to translate the ID's to Products to show in the view. One solution would be to first get all the products, and then go through the list one more time to add the count, but isn't there a better way to add the count already in the function to my repository?
public class CartItem
{
public int ProductID { get; set; }
public int Count { get; set; }
}
I made this model to put in my ViewModel, is that the correct approach or is there already a data structure for this?
public class CartProduct
{
public Product Product { get; set; }
public int Count { get; set; }
}
How can I easily add a method to my repository who convert my List of CartItems to a List of CartProducts without making a round trip to the database for every entry?
Sorry for the messy title and explanation, only been programming in C# for 2 weeks.
Upvotes: 0
Views: 4203
Reputation: 109245
First get the Product
s of the cart items from the database:
var prodIds = cartItems.Select(c => c.ProductID).ToList();
where cartItems
is your in-session collections of cart items.
var productsOfItems = db.Products
.Where(p => prodIds.Contains(p.ProductID)
.ToList();
Now create the view models:
var cartProducts =
(from p in productsOfItems
join c in cartItems on p.ProductID equals c.ProductID
select new CartProduct {
Product = p,
Count = c.Count
}).ToList();
Upvotes: 2
Reputation: 12462
You need to be more specific. If you're using an ORM like entity framework or nhibernate you can group by product id and then select your cartproduct model and the count.
public static List<Client> GetClientsWithTotalOrders()
{
//create DataContext object, use it, discard it:
using (CodeProjectDataContext db = new GetDataContext())
{
//join Client with Order:
var res = db.Clients // db is the data context
.Join(
db.Orders,
o => o.ID,
c => c.ClientID,
(c, o) => new { c }
)
//group by Client
.GroupBy(o => o.c)
//define output object
.Select(o => new { ID = o.Key.ID, AddressID = o.Key.AddressID,
Name = o.Key.Name, TotalOrders = o.Count() })
// here you won't select an anonymous type,
// you will select o => new CartProduct { Count = o.Count(),
// Product = new Product { // map your properties } }
//output to List of objects:
.ToList()
;
//cast the output sequence to List of Clients and return:
return (List<Client>)res;
}
};
Upvotes: 0