实体框架:通过动态更新的字段循环
问题描述:
全部,
我有一种情况,即进入的数据可能是使用多个版本之一,所以我希望能够使用循环更新记录而不是硬编码所有字段。
例如:
$
All,
I have a situation where the data coming in could be using one of several versions, so I want to be able to update the record using a loop instead of hard coding all the fields.
For example:
DataTable oDT = oLeadDetails.DefaultView.Table;
foreach (DataColumn oDC in oDT.Columns)
{
if (oDC.ColumnName.ToUpper() != "LEADID")
{
if (oDC.DataType == System.Type.GetType("System.DateTime"))
{
if (DateTime.TryParse(myLeadParser.GetElement(oDC.ColumnName), out dDateResult))
{
oLeadDetails.SetColumn(oDC.ColumnName, dDateResult);
}
}
else if (oDC.DataType == System.Type.GetType("System.Int32"))
{
if (Int32.TryParse(myLeadParser.GetElement(oDC.ColumnName), out iIntResult))
{
oLeadDetails.SetColumn(oDC.ColumnName, iIntResult);
}
}
else
{
oLeadDetails.SetColumn(oDC.ColumnName, StringHelper.StringStart(myLeadParser.GetElement(oDC.ColumnName), oDC.MaxLength));
}
}
}
oLeadDetails.Save();
实体框架中有类似的东西吗?我可以看到属性作为每个字段名称,但我无法看到通过它们枚举并使用类似SetColumn的内容
谢谢,
jax
Is there anything similar in the entity framework? I can see the properties as each field name, but there is no way I can see to enumerate through them and use something like SetColumn
Thanks,
jax
答
您好,您可以使用Reflection来枚举实体的属性。
使用Reflection为每个类的属性获取PropertyInfo对象。
然后迭代PropertyInfo对象并在循环内做任何你想做的事。
Hi,
You can use Reflection to enumerate through the entity's properties.
Use Reflection to get the PropertyInfo object for each of the class' Properties.
Then iterate over the PropertyInfo objects and inside the loop do whatever you want.