1

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 !

0

1 Answer 1

1

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

1 Comment

So Simple..I have been trying to handle this GetProperty() for 1 hour using the methode from : stackoverflow.com/questions/21084916/… Yours is better and probably faster. Thank you very much

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.