Jlo
Jlo

Reputation: 51

C# Entity Framework6 Specify the property of the table in parameter

My application must update a lot of parameters in my database (in different tables, parameters come in disorder). I just read a label (name) and a value, and must store the value in the correct place in the database according to the name.

For now I use a switch(), but this solution doesn't seem to be good as the treatment for each parameters is different and may become quite heavy in the future ( I have over 500 parameters).

Here is the code (with the switch for now)

private void MyFunc(int id, int value, string name_param){

using (var db = new mydatabaseEntities())
{
    var result = db.mytable.Where(b => b.id == id).First();

    switch (name_param){
         case "M12":
              result.m12 = value;
              break;
         case "M14":
              result.m14 = value;
              break;
         case "M16":
              result.m16 = value;
              break;
         //etc... 500 cases
     }
   db.SaveChanges();
   }
}

Would you know how to specify in parameter which property of my table I want to update :m12,m14, m16... (So I don't need to use a switch) ?

Thanks !

Upvotes: 1

Views: 35

Answers (1)

Ron Beyer
Ron Beyer

Reputation: 11273

You should be able to do it through reflection:

private void MyFunc(int id, int value, string name_param)
{
    using (var db = new mydatabaseEntities())
    {
        var result = db.mytable.Where(b => b.id == id).First();
        var prop = result.GetType().GetProperty(name_param);

        if (prop == null)
            throw new InvalidOperationException();    //Or something appropriate

        prop.SetValue(result, value);

        db.SaveChanges(); 
    }
}

Just be aware that this uses reflection and can be slow for doing a lot of operations. You can speed it up a little bit by caching the type information and the property.

By the way, if your name_param casing is different than the property name, you can narrow it down using LINQ:

var prop = result.GetType()
                 .GetProperties()
                 .Where(p => string.Compare(p.Name, param_name, true) == 0)
                 .FirstOrDefault();

Or just use the correct binding flags:

var prop = result.GetType().GetProperty(name_param, 
                              BindingFlags.IgnoreCase |
                              BindingFlags.Public | 
                              BindingFlags.Instance);

Upvotes: 1

Related Questions