Click here to Skip to main content
15,885,914 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
See more:
Hi,

In my REST Controller I have a HTTP/PUT handler method. The issue is that when I receive updates, I do not want to send everything over the wire if only one property has changed.

The way I do it now is having the handler accept a dynamic parameter, which I then apply to my LINQ objects by reflection.

It works, but it makes me feel dirty. There must be a better method?

Example Code (abbreviated):

C#
public void Put(dynamic value)
{
    var db = new MyContext();
    int id = (int)value.ID;
    Employee e = db.Employee.SingleOrDefault(r => r.ID == id);
    foreach (JProperty prop in value)
    {
        if (prop.Name != "ID" && prop.Name != "")
        {
            PropertyInfo pi = e.GetType().GetProperty(prop.Name);
            if (pi.CanWrite)
            {
                JToken jt = (JToken)prop.Value;
                var val = Convert.ChangeType(jt, pi.PropertyType);
                pi.SetValue(e, val, null);                            
            }
        }
    }
    db.SaveChanges();
}
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900