Q:

EF - How can I merge 2 lines of ShoppingCart into 1 if items are the same

If a user add the same product more than 1 time, I would like to merge those 2 lines into 1 line. How I can merge them in EF?
Here is my table.
CREATE TABLE [dbo].[CartDetail](
[Id] [int] IDENTITY(1,1) NOT NULL,
[CartId] [int] NOT NULL,
[ProductId] [int] NOT NULL,
[Qty] [decimal](10, 2) NOT NULL,
[Price] [decimal](18, 2) NOT NULL,
[Discount] [decimal](18, 2) NOT NULL,
[KDV] [decimal](18, 2) NOT NULL,
[CreatedDate] [datetime] NOT NULL,
[Active] [bit] NOT NULL,

I would like to explain the way that I want merge them by an old school SQL script
Select CartId,
       ProductId,
       SUM(Qty),
       Price,
       Discount,
       KDV
 From CartDetail
 Group By CartId, ProductId, Price, Discount, KDV

Regards

A:

Instead of generating INSERT you should search for previous record with same ProductId (and CartId of course) and call Add(...) only when nothing is found. When something found - increment Qty and update existing record:
var existingLine = await db.CartDetails
    .FirstOrDefaultAsync(x => x.CartId == cartId && x.ProductId == productId);
if (existingLine == null) 
{
    db.CartDetails.Add(new CartDetails() 
    {
        CartId = cartId,
        ProductId = productId,
        Qty = 1,
        ...
    });
}
else 
{
    existingLine.Qty += 1;
}
await db.SaveChangesAsync();

