3

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 assign 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

1

1 Answer 1

2
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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.