繁体   English   中英

Linq2sql表:列表 <fieldname> 作为参数

[英]Linq2sql table: List<fieldname> as parameter

所以,我想更新我的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();
}

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

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();
    }
}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM