c# - Add or Update a Record? -


I have an MVC application with the following code in the controller's POST method. I am adding an EF and it is obvious that this is not correct. I want to add a record if it does not exist, otherwise update. How can I go about doing this?

  try {attributeEntities db = new attributeEntities (); IEnumerable & LT; String & gt; Item = ViewModel. Selected element 2; Int i = 0; Foreign objects (different items in items) {var temp = item; // Save it selected HarmonyTribute feature = new selectedHermNetItit (); Attribute.CustomLabel = viewModel.ItemCaptionText; Attribute.isvisible = viewModel.Isselected; String Harmony AttributeID = item.Substring (1, 1); // attribute.OrderNumber = Convert.ToInt32 (order); Attribute.OrderNumber = i ++; Attribute.HarmonyAttribute_ID = Convert toInt32 (Goodwill AttributeID); Db.SelectedHarmonyAttributes.Add (attribute); Db.SaveChanges (); }}  

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

db. Selected HarmonyAttributes.AddOrUpdate (attribute); Db.SaveChanges (); Edit: I'm assuming that the selected Harmonic Attributes type is of DbSet

EDIT2: only to blame it in this way (and this is for you It can not be worried), that your organization is not responsible for the change of its own state. This means that you can update any property unit for invalidity, where you internally own it unit But want to be valid Awareness is that you always want more processing updates. If these things are a matter of concern to you, then you should add a public update method to the organization and first check its existence on the database. Ex:

  var attribute = db Selected Harmony Properties SingleLow Default (x => x.HarmonyAttribute_ID == Goodwill Specialty ID); If (attribute! = Null) {attribute.Update (viewModel.ItemCaptionText, viewModel.Iselected, i ++); } Else {attribute = new attribute (viewModel.ItemCaptionText, viewModel.Iselected); Db.SelectedHarmonyAttributes.Add (attribute); } Db.SaveChanges ();  

Your update method might look like this:

  Public Zero update (string custom label, boole, ineligible, int order number) {if (! MyValidationMethod ()) {New MyCustomException (); } CustomLabel = Custom Label; Isvisible = invisible; OrderNumber = orderNumber; PerformMyAdditionalProcessingThatIAlwaysWantToHappen (); }  

Then protect the properties of all institutions "get" public but protect "set" so that they can not be updated from outside of the unit. This can be a small part of a tangent, but by using the addOrUpdate method, you can assume that no update should be controlled and preventing your domain unit from being included in an invalid state. Hope it helps!


Comments