4

i have a function

public string getValue(string val)

and in this function i need to get the value from a database field:

using (UsersContext db = new UsersContext())
{
    UserProfile user = db.UserProfiles.Where(c => c.UserId == this.userId).FirstOrDefault()
    name = user.(val); ????????????
}

How i can get the custom value from the function argument? I think i need to change the argument type:

public string getValue(UserProfile val)

But how i can get the Property or Pass the Property Name?

Thank you!!! :)

tereško
  • 58,060
  • 25
  • 98
  • 150
  • What is the parameter val? Does it specify the property name that you want to access? – Georg Feb 19 '14 at 13:37
  • Help me understand. This GetValue method should take as a parameter name of the property that you would like to get from an object that is fetched from database? Is it always the same type of object that you getting from db ? if so why don't you just return the object ? – Lukasz S Feb 19 '14 at 13:38
  • This sounds like a job for stored procedures. – asawyer Feb 19 '14 at 13:41
  • yes this is logic. its my fault sorry! i can return or store the UserProfile Object. – Konstantin XFlash Stratigenas Feb 19 '14 at 13:43
  • You can make use of Dynamix Linq for accessing data by field names. Here is the link for the library: http://dynamiclinq.codeplex.com/ – Shashank Chaturvedi Feb 19 '14 at 13:46

1 Answers1

2

It is generally easier and more performant of you pass in the property as a function than as a string, i.e. change your signature to

public string GetValue<T>(Func<UserProfile, T> property)

(Naming conventions in .NET are that methods are to be in Pascal Case.) With this, you can then call name = property(user).

Alternatively, you can use the string to retrieve the PropertyInfo object and use this to retrieve the property value. However, this is less performant as it requires reflection.

Georg
  • 5,626
  • 1
  • 23
  • 44