Majid Basirati
Majid Basirati

Reputation: 2855

Delete entity if it exist, Add it if not exist in Entity Framework

I want to remove entity from my context if it exist in database and if it is not exist, it's added to database.

How can I do this using EntityState in Entity Framework?

I want something like this:

var fav = new ProductFavorite()
{
    ProductId = productId,
    UserId = User.Identity.GetUserId()
};

if (_db.Entry(fav).State == EntityState.Detached)
{
    _db.Entry(fav).State = EntityState.Added;
}
else
{
    _db.Entry(fav).State = EntityState.Deleted;
}

_db.SaveChanges();

What is the best way for do this?

Upvotes: 0

Views: 6893

Answers (3)

Babacar Diop
Babacar Diop

Reputation: 21

You are supposed to load the element from the database before detach it. Why don't you try this instead :

  //You should set the value of productId and userId first
  // Assuming _db.Products is your DbSet<Product> property in the DbContext class

  var fav = _db.Products.FirstOrDefault(x => x.ProductId = productId && x.UserId == userId);

  if(fav == null){
  //That mean you should add the element
    _db.Products.Add(fav);
  }
  else{
    _db.Products.Remove(fav);
  }

  _db.SaveChanges();

The use of the EntityState is recommended when you are in a disconnected scenario, but if you are using a single DbContext, it is not a good approach.

Upvotes: 0

big_water
big_water

Reputation: 3204

I would suggest using Linq queries to accomplish this. Something to the tune of:

        var existingEntry = _db.ProductsTable.FirstOrDefault(s => s.ProductId == productId);
        if (existingEntry != null)
        {
            _db.ProductsTable.Remove(existingEntry);
        }
        else
        {
            _db.ProductsTable.Add(new ProductFavorit()
            {
                ProductId = productId,
                UserId = User.Identity.GetUserId()
            });
        }
        _db.SaveChanges();

Replace "ProductsTable" with your table name in your context and include "using System.Linq;" at the top of your file.

Upvotes: 0

Michael Coxon
Michael Coxon

Reputation: 5510

So I am not sure of your solution, but I think you might be trying to mix functionality here at a too low level. My suggestion would be to do this at a higher level and try and get the existing favourite then remove it or add it if it is null...

public class FavoriteService
{
    ...

    public void ToggleFavourite(int productId, int userId)
    {
        using (context = new MyDbContext())
        {
            var fav = context.ProductFavorites
                .SingleOrDefault(f => f.ProductId == productId && f.UserId == userId);

            if(fav != null)
            {
                context.ProductFavorites.Remove(fav);
            } 
            else 
            {
                context.ProductFavorites.Add(new ProductFavorite
                {
                    ProductId = productId,
                    UserId = userId
                });
            }

            context.SaveChanges();
        }
    }

    ...
}

Upvotes: 1

Related Questions