【问题标题】:Linq2sql table: List<fieldname> as parameterLinq2sql 表:List<fieldname> 作为参数
【发布时间】:2013-08-01 14:11:09
【问题描述】:

所以,我想更新我的 items 表的某些字段:

internal void FieldsUpdate(string id, System.Collections.Hashtable fieldsWithChanges, List<string> keysToUpdate)
{
    using (DBDataContext db = new DBDataContext())
    {
        item myItem = db.items.Single(t=>t.id==id);
        keysToUpdate.ForEach(key => {
            myItem[key] = GetValue(fieldsWithChanges, key).ToString(); 
            //Or something like that, I'm inventing that index 
        });
        db.SubmitChanges();
    }
}

myItem[key]不存在,我该怎么做呢?

这是我所知道的糟糕的选择:

internal void FieldsUpdate(string id, System.Collections.Hashtable fieldsWithChanges, List<string> keysToUpdate)
{
    using (DBDataContext db = new DBDataContext())
    {
        item myItem = db.items.Single(t=>t.id==id);
        keysToUpdate.ForEach(key => {
            if (key=="thisKey")
                myItem.thisKey = GetValue(fieldsWithChanges, key).ToString(); 
                // really awful. So What this condition for every colname? thats unsustainable.
        });
    }
    db.SubmitChanges();
}

【问题讨论】:

  • keys 应该是 keysToUpdate 吗?
  • 你说得对,对不起。 (但这不是问题,但我会更改它以避免混淆)谢谢!

标签: c# linq tsql linq-to-sql


【解决方案1】:

您可以通过使用反射设置属性值来完成此操作。

internal void FieldsUpdate(string id, System.Collections.Hashtable fieldsWithChanges, List<string> keysToUpdate)
{
    using (DBDataContext db = new DBDataContext())
    {
        item myItem = db.items.Single(t=>t.id==id);
        keysToUpdate.ForEach(key => {
            typeof(item).GetProperty(key)
                .SetValue(item, GetValue(fieldsWithChanges, key), null);
        });
        db.SubmitChanges();
    }
}

这不是最高效的解决方案。

如果这是您需要维护的模式,我建议您研究代码生成。

【讨论】:

  • 你的意思是一路反射?,可维护性也是一个问题,这就是为什么我一直试图避免它。不过,这可以解决问题,非常感谢!
  • 我不知道你的意思。我已经编辑了我的答案,使其更加清晰。该解决方案会起作用,但对于大量更新来说会很慢。
  • 我还有一个问题:GetValue 返回一个object,但keyHashtable 值是另一个type(实际上与命运键字段的类型相同)... 封装到对象和解封装是否不需要任何必要的铸件?还是我应该考虑一个 方法?
  • 如果是同类型的,会的。试试看,让我知道结果:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多