Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用LINQ更新迭代列列表的实体列_Linq_Linq To Sql - Fatal编程技术网

使用LINQ更新迭代列列表的实体列

使用LINQ更新迭代列列表的实体列,linq,linq-to-sql,Linq,Linq To Sql,我可以使用LINQ从表中获取列列表,如下所示: OrderDataContext ctx = new OrderDataContext(); var cols = ctx.Mapping.MappingSource .GetModel( typeof( OrderDataContext ) ) .GetMetaType( typeof( ProductInformation ) )

我可以使用LINQ从表中获取列列表,如下所示:

OrderDataContext ctx = new OrderDataContext();
var cols = ctx.Mapping.MappingSource
                        .GetModel( typeof( OrderDataContext ) )
                        .GetMetaType( typeof( ProductInformation ) )
                        .DataMembers;
ProductInformation info = new ProductInformation();
info.SomeField1 = val1;
info.SomeField2 = val2;

ctx.ProductInformation.InsertOnSubmit( info );
ctx.SubmitChanges();
这将提供列列表,因此我可以执行以下操作:

foreach ( var col in cols )
{
    // Get the value of this column from another table
    GetPositionForThisField( col.Name );
}  
所以这一切都是可行的,我可以迭代列列表,从另一个表中提取这些列的值(因为列名是另一个表中的键),所以我不必做切换…或者很多if…then

现在的问题是:

获取这些值后,如何填充实体以将其保存回去?我通常会这样说:

OrderDataContext ctx = new OrderDataContext();
var cols = ctx.Mapping.MappingSource
                        .GetModel( typeof( OrderDataContext ) )
                        .GetMetaType( typeof( ProductInformation ) )
                        .DataMembers;
ProductInformation info = new ProductInformation();
info.SomeField1 = val1;
info.SomeField2 = val2;

ctx.ProductInformation.InsertOnSubmit( info );
ctx.SubmitChanges();
但是,当没有以下情况时,如何使用上面的同一列集合来填充列,同时对其进行迭代:

info["field1"].Value = val1;

谢谢。

只需获取要修改的对象,设置属性并调用SubmitChanges即可。无需创建新对象并插入它。上下文跟踪更改的属性并相应地生成update语句。在您的情况下,您可能希望通过反射而不是手动设置属性,因为您正在从另一个表中读取它们。

只需获取要修改的对象,设置属性并调用SubmitChanges即可。无需创建新对象并插入它。上下文跟踪更改的属性并相应地生成update语句。在您的情况下,您可能希望通过反射而不是手动设置属性,因为您是从另一个表中读取它们。

您需要使用反射。假设您可以从元数据中获取
属性info

PropertyInfo property = GetPropertyForThisField(col.Name);
property.SetValue(info, val1, null);

你需要使用反射。假设您可以从元数据中获取
属性info

PropertyInfo property = GetPropertyForThisField(col.Name);
property.SetValue(info, val1, null);