0

I have an MVC application with the following code in the POST method of the controller. I am doing an EF Add and obviously that is not right. I want it to add the record if it doesn't exist, otherwise Update. How can I do that please?

try
{
    AttributeEntities db = new AttributeEntities();
    IEnumerable<string> items = viewModel.SelectedAttributes2;
    int i = 0;
    foreach (var item in items)
    {
        var temp = item;

        // Save it
        SelectedHarmonyAttribute attribute = new SelectedHarmonyAttribute();
        attribute.CustomLabel = viewModel.ItemCaptionText;
        attribute.IsVisible = viewModel.Isselected; 
        string harmonyAttributeID = item.Substring(1, 1);
        // attribute.OrderNumber = Convert.ToInt32(order);
        attribute.OrderNumber = i++;
        attribute.HarmonyAttribute_ID = Convert.ToInt32(harmonyAttributeID);

        db.SelectedHarmonyAttributes.Add(attribute);
        db.SaveChanges();
    }
}
user247702
  • 23,641
  • 15
  • 110
  • 157
user2471435
  • 1,644
  • 7
  • 35
  • 62
  • you will need to store the ID of the attribute you're trying to save, check if it exists in the database. if it does, update its properties and save changes. If not, then create it and add it. – DLeh Oct 27 '14 at 15:36
  • Check the answer on this post. [here][1] [1]: http://stackoverflow.com/questions/6966207/entityframework-insert-if-not-exist-otherwise-update – 4nis Oct 27 '14 at 16:09

3 Answers3

1

You would need to check the database for the record you are trying to add/update. If the look-up returns null, that means that it doesn't exist in the database. If it does, you can modify the record that you looked up and call db.SaveChanges() to persist the changes you made to the database.

Edit:

int id = Convert.ToInt32(harmonyAttributeID);
var existingEntry = db.SelectedHarmonyAttributes.SingleOrDefault(x => x.HarmonyAttribute_ID == id);
JB06
  • 1,881
  • 14
  • 28
0

One common way to determine an add or update is by simply looking at an identifier field, and setting the appropriate state.

using System.Data;

SelectedHarmonyAttribute attribute;

using (var db = new YourDbContext())
{
    db.Entry(attribute).State = attribute.HarmonyAttribute_ID == 0 ? EntityState.Added : EntityState.Modified;

    db.SaveChanges();
}
mallocation
  • 241
  • 2
  • 6
-1

You could import the System.Data.Entity.Migrations namespace and use the AddOrUpdate extension method:

db.SelectedHarmonyAttributes.AddOrUpdate(attribute);
db.SaveChanges();

EDIT: I'm assuming that SelectedHarmonyAttributes is of type DbSet

EDIT2: Only drawback with doing it this way (and it may not be a concern for you), is that your entity isn't responsible for it's own state change. This means that you can update any property of the entity to something invalid, where you might want to internally validate it on the entity itself or maybe do some other processing you always want to occur on update. If these things are a concern for you, you should add a public Update method onto the entity and check for its existence on the database first. e.g:

var attribute = db.SelectedHarmonyAttributes.SingleOrDefault(x => x.HarmonyAttribute_ID == harmonyAttributeID);

if (attribute != null)
{
    attribute.Update(viewModel.ItemCaptionText, viewModel.Isselected, i++); 
}
else
{
    attribute = new Attribute(viewModel.ItemCaptionText, viewModel.Isselected);
    db.SelectedHarmonyAttributes.Add(attribute);
}

db.SaveChanges();

Your update method might look something like:

public void Update(string customLabel, bool isVisible, int orderNumber)
{
    if (!MyValidationMethod())
    {
        throw new MyCustomException();
    }

    CustomLabel = customLabel;
    IsVisible = isVisible; 
    OrderNumber = orderNumber;

    PerformMyAdditionalProcessingThatIAlwaysWantToHappen();
}

Then make all of the entities' properties public "get" but protected "set" so they can't be updated from outside the entity itself. This might be going off an a bit of a tangent but using the AddOrUpdate method would assume you don't want to control the way an update occurs and protect your domain entity from getting into an invalid state etc. Hope this helps!

  • Be careful. That's not what it is designed for....http://thedatafarm.com/data-access/take-care-with-ef-4-3-addorupdate-method/ – Colin Oct 27 '14 at 16:45
  • Yes, I realised after I posted the answer that it does have its drawbacks. I've edited my answer to qualify it a bit further but it may be suitable if the drawbacks are understood and the primary key to compare against is known. (In this example it looks like HarmonyAttribute_ID is the primary key) – PrisonerSix Oct 27 '14 at 17:15