Reputation: 6103
Here is how I get data from database and update using lambda expression .
item _myItem = db.myDBContext.items.Where(x => x.id == 0).SingleOrDefault();
_myItem.field1 = "myValueForField1";
_myItem.field2 = "myValueForField2";
_myItem.field3 = "myValueForField3";
_myItem.field4 = "myValueForField4";
db.myDBContext.SubmitChanges();
It's just a sample, my table has many columns.
If I follow this way, I have to assign each column (field1,field2,..).
If I have 20 columns, I have to write 20 lines of code.
Can I assign field name dynamically ?
Like
_myItem[dynamicFieldName] = ...;
Or is there any way to make it better ?
I just want to assign the field names dynamically.
Upvotes: 1
Views: 1465
Reputation: 1015
Try this one:
item _myItem = db.myDBContext.items.Where(x => x.id == 0).SingleOrDefault();
var typ = typeof(item);
typ.GetProperties().ToList().Foreach(m=> m.SetValue(_myItem,"yourvalue", null));
db.myDBContext.SubmitChanges();
Upvotes: 1
Reputation: 1239
You can not use reflection.
You would make indexer in your Item class. And use extension methods to convert to specific type.
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
static class MyExtensions
{
public static int toInt32(this string field)
{
return Convert.ToInt32(field);
}
}
class MySpecificList
{
Dictionary<string, string> _fields = new Dictionary<string, string>();
public string this[string name]
{
get
{
return _fields[name];
}
set
{
_fields[name] = value;
}
}
static void Main(string[] args)
{
MySpecificList list = new MySpecificList();
list["field1"] = "1";
Console.WriteLine(list["field1"].toInt32() + 1);
}
}
}
Upvotes: 0
Reputation: 136114
Without using reflection, you cannot assign fields dynamically in that way.
Using reflection, you can, but there is a performance hit associated.
for example:
var myField = "field1";
var field = _item.GetType().GetField(myField); // perhaps GetProperty() - depending on if its a field or a property.
field.SetValue(_item,"myValueForField1");
Obviously that can be done in a loop, with all your field names in an array or list of some sort.
Upvotes: 1
Reputation: 2352
You can use reflection:
PropertyInfo pInfo = _myItem.GetType().GetProperty("field2"):
pInfo.SetValue(_myItem, "myValueForField2");
Upvotes: 0