Bryan_James
Member
Hi! I am trying to create my own ORM. Database fields will be the same name as the class variables of the model. Now, I searched for a way to get column name in SqlDataReader in C#. In my code, "ListAllVars()" lists the variables in C#:
Now that I have variable names of the class and column names of a table, I want to assign a value to a variable in a class through the column name (which is also a string). Like so:
Is there any way to achieve it?
C#:
public interface IBaseModel
{
void ListAllVars();
}
public class BaseModel : IBaseModel
{
protected string tableName = "old table name";
protected string timestamp = "some stamp";
public void ListAllVars()
{
BindingFlags bindingFlags = BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.Static;
foreach (FieldInfo field in this.GetType().GetFields(bindingFlags))
{
Console.WriteLine(field.Name);
}
}
}
public interface IModel : IBaseModel
{
int IntegerMember { get; set; }
string StringMember { get; set; }
string ModelName { get; set; }
void PrintHello();
}
public class Model : BaseModel, IModel
{
private int integerMember;
private string stringMember;
private string modelName;
private string tableName = "new table name";
public int IntegerMember
{
get => this.integerMember;
set => this.integerMember = value;
}
public string StringMember
{
get => this.stringMember;
set => this.stringMember = value;
}
public string ModelName
{
get => this.modelName;
set => this.modelName = value;
}
}
Now that I have variable names of the class and column names of a table, I want to assign a value to a variable in a class through the column name (which is also a string). Like so:
C#:
int userID = 0;
string fieldName = "userID";
string fieldValue = "18";
_some_function_or_method(fieldValue).value(Convert.ToInt32(fieldValue));
Console.WriteLine("User ID value: " + userID);
// outputs "User ID value: 18"
Is there any way to achieve it?