问题
I have a Web Api project and currently updating an entity is done via POST. Creating an entity is also done via the same POST method, and I implement by checking if the user has sent me an entity Id and then implementing an update as opposed to a create.
This is bad good for a number of obvious reasons. It's also confusing from a client perspective and makes the whole method slow and hard to define.
So I'm splitting updating into a PUT method, and I want it to be like so (psuedo code)
public string PUT(MyModel model){
//Check if model Id is sent. return if not.
//Check what other fields have been sent.
//Update only those fields using EF and save.
}
I would implement like:
var toUpdate = context.MyModels.FirstOrDefault(x => x.Id == model.Id);
if(toUpdate == default(MyModel)){ //Return error to client }
if(model.first != null){ toUpdate.first = model.first; }
//Repeat for every field.
context.MyModels.AddOrUpdate();
context.SaveChanges();
As I'm new to building API's I wondered if this is standard for creating PUT update methods. This might get closed as Opinion-based but I'd like to know if this implementation is okay as I've had no guidance in building this API really.
回答1:
For your case, I think you can implement like this.
try
{
context.Entry<MyModel>(model).State = EntityState.Modified;
context.SaveChanges();
}
catch (DbEntityValidationException dbEx)
{
var msg = dbEx.EntityValidationErrors.Aggregate(string.Empty, (current1, validationErrors) => validationErrors.ValidationErrors.Aggregate(current1, (current, validationError) => current + (Environment.NewLine + $"Property: {validationError.PropertyName} Error: {validationError.ErrorMessage}")));
var fail = new Exception(msg, dbEx);
throw fail;
}
Actually, I prefer putting update code inside generic class, so that I don't need to write the update code for every entity
public void DoUpdate<TEntity>(TEntity entity) where TEntity : class
{
try
{
Context.Entry(entity).State = EntityState.Modified;
Context.SaveChanges();
}
catch (DbEntityValidationException dbEx)
{
var msg = dbEx.EntityValidationErrors.Aggregate(string.Empty, (current1, validationErrors) => validationErrors.ValidationErrors.Aggregate(current1, (current, validationError) => current + (Environment.NewLine + $"Property: {validationError.PropertyName} Error: {validationError.ErrorMessage}")));
var fail = new Exception(msg, dbEx);
throw fail;
}
}
来源:https://stackoverflow.com/questions/32826420/easiest-way-to-implement-put-api-method-to-update-entity