【问题标题】:How do I update single field value using Reflection in LINQ如何在 LINQ 中使用反射更新单个字段值
【发布时间】:2012-08-23 12:30:47
【问题描述】:

我收到来自客户端回发的两个变量,它们匹配“字段名”和“值”。字段名可以是我在 db 表列中拥有的 50 个字段之一。

如何使用反射来识别哪个回发字段名与表中的字段匹配,然后使用 LINQ 更新传回的值更新该单个字段?

(string fieldid, string fieldvalue)

更新:我看过Dynamically select and update a column value in LINQ resultset

而不是在页面上设置特定的 TExtBox,我需要将反射变量字段的值写回 db?这是我希望了解更多信息的地方。

【问题讨论】:

  • 您所说的“LINQ 更新”是什么意思? LINQ 是一种用于“查询”而非更新的查询语言。
  • 是的,对不起...通常,我会从数据库中查询一行,如下所示:var query = from d in connection.Get().ToList () where d.username == AUsername select d; 然后设置一些字段变量并使用更新:connection.Update(query);
  • 其中connection.Get和connection.Update已经是类方法了。
  • 您“查看”的问题不会设置文本框,而是将名为“fieldname”的数据库字段设置为文本框的内容,因此工作方式相同如果您将 textbox.Text 替换为变量。

标签: linq dynamic reflection lambda insert-update


【解决方案1】:

如果在编译类型时您的源名称和目标名称都不知道,那么您可以使用反射来读取和设置值,例如

public void SetField<T1, T2>(T1 destination, string destinationFieldName, 
                             T2 source     , string sourceFieldName)
{  
    FieldInfo destFi    = typeof(T1).GetField(destinationFieldName);
    FieldInfo sourceFi  = typeof(T2).GetField(sourceFieldName);

    if (sourceFi != null && destFi != null)
        destFi.SetValue(destination, sourceFi.GetValue(source));
}

然后,如果您尝试将名为 NewName 的字段从设置(它是名为 Settings 的类的实例)复制到类型为 Table1 的记录的列名,那么您可以这样做:

SetField<Table1, Settings<(record , "Name" , settings , "NewName");

如果你使用的是属性而不是字段,那么你需要使用 PropertyInfo 而不是 FieldInfo

public void SetProperty<T1, T2>(T1 destination, string destinationFieldName, 
                                T2 source, string sourceFieldName)
{
    PropertyInfo destPi     = typeof(T1).GetProperty(destinationFieldName);
    PropertyInfo sourcePi  = typeof(T2).GetProperty(sourceFieldName);

    if (sourcePi != null && destPi != null)
        destPi.SetValue(destination, sourcePi.GetValue(source , null) , null);
}

显然使用这样的东西会影响性能。

【讨论】:

  • 感谢您的投入 - 它肯定比我目前使用的更紧凑和灵活。我将对两者进行测试以考虑性能影响。
猜你喜欢
  • 2013-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多