0

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?

3
  • Have you tested what you posted? What is the issue? Are you receiving any errors? Commented Oct 26, 2016 at 14:16
  • @BviLLe_Kid Yes, Always EntityState of fav entity is Detached Commented Oct 26, 2016 at 14:19
  • Sorry, I don't quite understand. Are you receiving an exception? Or the conditional statement is working as expected? Commented Oct 26, 2016 at 14:22

3 Answers 3

1

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();
        }
    }

    ...
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.