Editing and Updating Entity Framework entity in ASP .NET MVC
I have an entityframework entity called "ABC" (attributes ID and Title).
On update record view, I have added the ID as hidden field and title is the text box.
Controller looks like something:
public ActionResult UpdateAction( ABC obj )
I get everything fine and fair in obj - i.e., the title, and the ID.
Now to update the record in database, I read the original entity:
var original = (from x in base.context.ABC where x.id == obj.id ).Single();
Now to reflect the changes in original, I think should do the update model:
this.TryUpdateModel( original );
I get an error :| ... stating that column ID cannot be changed.
The property 'id' is part of the object's key information and cannot be modified.
I do not want to manually as开发者_C百科sign the properties back to original object.
The other alternative can be:
TryUpdateModel(original, new string[] { "Title" }, form.ToValueProvider());
But I hate strings - also, my object has like 20 attributes :|
Can someone please suggest a better pattern of doing so?
Rgds
public class ControllerExt : Controller
{
protected void UpdateModel<TModel>(TModel model, params Expression<Func<TModel, object>>[] property) where TModel : class
{
var props = new List<string>(property.Length);
foreach (var p in property)
{
var memberExpression = RemoveUnary(p.Body) as MemberExpression;
if (memberExpression == null)
{
throw new NullReferenceException("Can not retrieve info about member of {0}".FormatThis(typeof(TModel).Name));
}
props.Add(memberExpression.Member.Name);
}
this.UpdateModel(model, props.ToArray());
}
private static Expression RemoveUnary(Expression body)
{
var unary = body as UnaryExpression;
if (unary != null)
{
return unary.Operand;
}
return body;
}
}
Example:
UpdateModel<MyModel>(model, x => x.PropertyFromMyModel_1, x => x.PropertyFromMyModel_2);
精彩评论