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

share|improve this question

I think I have found a solution @ stackoverflow.com/questions/922402/… – effkay Jan 24 '10 at 16:42
feedback

1 Answer

up vote 2 down vote accepted
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);
share|improve this answer
thanks... will try; – effkay Jan 25 '10 at 12:56
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.