Vijay P.V
Vijay P.V

Reputation: 145

Remove row using linq

How to delete a record from database using linq and entity framework.

    public void DeleteCartItem(string customerId, string storeId, string productId)
    {
        //Authenticate service            
        Authenticate();
        int _customerId = Convert.ToInt32(customerId);
        int _storeId = Convert.ToInt32(storeId);
        int _productId = Convert.ToInt32(productId);
        var _cartid = (from c in context.carts
            where c.CustomerId == _customerId && c.StoreId == _storeId && c.ProductId ==_productId
            select c.CartId);
        context.carts.Remove();
    }

Above mentioned code is not working. I want to delete based on three parameters which are passed in this method.

Upvotes: 1

Views: 2563

Answers (1)

ATP
ATP

Reputation: 561

If you are using EntityFramework 6 then can you please try like below:

public void DeleteCartItem(string customerId, string storeId, string productId)
    {
        //Authenticate service            
        Authenticate();
        int _customerId = Convert.ToInt32(customerId);
        int _storeId = Convert.ToInt32(storeId);
        int _productId = Convert.ToInt32(productId);
        var _cartid = (from c in context.carts
            where c.CustomerId == _customerId && c.StoreId == _storeId && c.ProductId ==_productId
            select c);
        context.carts.RemoveRange(_cartid );
        context.SaveChanges();
    }

Or a quick one can be:

context.carts.RemoveRange(context.carts.Where(c => c.CustomerId == _customerId && c.StoreId == _storeId && c.ProductId ==_productId));
context.SaveChanges();

Upvotes: 3

Related Questions