public vmTransactionResult <Contact> CreateContact(Contact model) { try { if (model.Id == 0) { _context.Contacts.Add(model); _context.SaveChanges(); return(new vmTransactionResult <Contact>() { Message = "New Contact " + model.FirstName + " " + model.LastName + " created successfully.", Object = model, StatusCode = 200 }); } else { var entry = _context.Entry <Contact>(model); DbSet <Contact> dbSet = _context.Set <Contact>(); // Retreive the Id through reflection var pkey = dbSet.Create().GetType().GetProperty("Id").GetValue(model); if (entry.State == EntityState.Detached) { var set = _context.Set <Contact>(); Contact attachedEntity = set.Find(pkey); // access the key if (attachedEntity != null) { var attachedEntry = _context.Entry(attachedEntity); attachedEntry.CurrentValues.SetValues(model); } else { entry.State = EntityState.Modified; // attach the entity } } _context.SaveChanges(); return(new vmTransactionResult <Contact>() { Message = "Contact " + model.FirstName + " " + model.LastName + " updated successfully.", Object = model, StatusCode = 200 }); } } catch (Exception ex) { return(new vmTransactionResult <Contact>() { Message = "Contact not created.try again!" + ex.Message, Object = null, StatusCode = -0 }); } }