1

I have a database table in SQL Server and I need to configure a .NET application to use some of the data in this table, this data is used in a SOAP API call.

For example, the table has these columns

FirstName | LastName | EmailAddress

The values in these columns need to map to certain fields in the API call. This configuration must be flexible, so I cannot just assign FirstName to apiobject.firstname, for example.

Is there a way to derive a string to a property of an object?

For example, for FirstName, would it be possible to resolve it to object.Firstname = value but not doing it like this

if(column == "FirstName")
{
    ApiObject.FirstName = columnValue
}

Rather I would want to do something like

ApiObject.[somehow-resolve-which-field] = columnValue

Does anyone know what I am on about?

andrewb
  • 2,995
  • 7
  • 54
  • 95

2 Answers2

2

If you does not have notation of this class and you simply want to create an object with required properties - the right way is to use dynamic, as it noted in other answers.

If you already have a class, for example:

public class MyClass
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string EmailAddress { get; set; }
}

You can do what you want with reflection as following:

var myObject = new MyClass();
var prop = myObject.GetType().GetProperty(column);
prop.SetValue(myObject, columnValue);

Where column and columnValue are from your example. Note that column should be of string type and columnValue should match the type of property.

Mikhail Tulubaev
  • 4,141
  • 19
  • 31
0

If I correctly understood you need an object which you don't know how many properties have it and what are these properties. For this situations there is dynamic keyword in c#. You can initialize your ApiObject as dynamic

dynamic ApiObject = new ExpandoObject();

then you can set properties of this object as following:

ApiObject.YourProperty=columnValue;

more details: About ExpandoObject

UPDATE
if you want to know which column is this, there is a ColumnName of DataTable of System.Data namespace. There are some issues for getting columns of table in c#. One of them is: How do I get column names to print in this C# program?

Community
  • 1
  • 1
Farid Imranov
  • 2,017
  • 1
  • 19
  • 31