Editing and updating an Entity Framework object in ASP.NET MVC

I have an entityframework called ABC (Attribute Identifier and Title).

In the update record window, I added the identifier as a hidden field, and the title as a text field.

The controller looks something like:

public ActionResult UpdateAction( ABC obj )

I get everything beautiful and fair in obj - that is, the name and identifier.

Now, to update the record in the database, I read the source object:

var original = (from x in base.context.ABC where x.id == obj.id ).Single();

Now, to reflect the changes in the original, I think we need to make an update model:

this.TryUpdateModel( original );

I get an error: | ... indicating that the column identifier cannot be changed.

The property 'id' is part of the object key information and cannot be modified. 

I do not want to manually assign properties back to the original object.

Another alternative could be:

TryUpdateModel(original, new string[] { "Title" }, form.ToValueProvider());

But I hate strings - also my object has 20 attributes: |

Can anyone suggest a better example?

Rgds

+3
1
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;
    }
}

:

UpdateModel<MyModel>(model, x => x.PropertyFromMyModel_1, x => x.PropertyFromMyModel_2);
+2

Source: https://habr.com/ru/post/1729784/


All Articles