abc123
abc123

Reputation: 262

selecting single column value by passing column name dynamically

I am passing column name dynamically and trying to get the value of that column from database here is code

public ActionResult GetValue(string colname)
{
     var obj= Activator.CreateInstance(Assembly.GetExecutingAssembly().GetType("Demo.Models.DEMOTABLE");
     var res = MvcApplication.dbm.Set<DEMOTABLE>().SqlQuery("Select * from DEMOTABLE");
     var colvalue = from e in res select e.GetType().GetProperty(colname).GetValue(obj,null);

      return View(colvalue);
}

i am getting the proper values in obj and res but not able to get column values in colvalue. It has the specific rows but the value is null i.e it is not able to asign value from res.

What am i doing wrong? Is there any proper method to do it? Please help!

Upvotes: 0

Views: 383

Answers (2)

abc123
abc123

Reputation: 262

I had done a mistake in my code and i have found a solution to it

instead of

var colvalue = from e in res select e.GetType().GetProperty(colname).GetValue(obj,null);

i changed to

var colvalue = from e in res select obj.GetType().GetProperty(colname).GetValue(e, null);

i was not passing data in GetValue to assign colvalue.

Upvotes: 0

VIJAY
VIJAY

Reputation: 849

Try this out, instead of line no 7 use the Entity call and the genericChildObjects will hold column value retrieved from Database.

    private void GetValue(string columnName)
    {
        var aClassType = Assembly.GetExecutingAssembly().GetType("ConsoleApplication8.A");
        Type list = typeof(List<>).MakeGenericType(new[] { aClassType });
        var genericChildObjects = (IList)Activator.CreateInstance(list);

        var res = new List<B> { new B() { TestData = "Test Data From Calss B" } };

        res.ForEach(
            r =>
                {
                    var aClassObject = Activator.CreateInstance(aClassType);
                    aClassType.GetProperty(columnName)
                              .SetValue(aClassObject, r.GetType().GetProperty(columnName).GetValue(r));
                    genericChildObjects.Add(aClassObject);
                });
    }

Upvotes: 1

Related Questions