使用 LINQ 迭代 col 列表来更新实体列
我可以使用 LINQ 从表中获取列列表,如下所示:
OrderDataContext ctx = new OrderDataContext();
var cols = ctx.Mapping.MappingSource
.GetModel( typeof( OrderDataContext ) )
.GetMetaType( typeof( ProductInformation ) )
.DataMembers;
这给了我列列表,因此我可以这样做:
foreach ( var col in cols )
{
// Get the value of this column from another table
GetPositionForThisField( col.Name );
}
所以这一切都有效,我可以迭代列列表并从另一个表中提取这些列的值(因为列名是另一个表中的键),所以我不必进行 switch.... 或很多 if...then...
现在的问题是:
在获得这些值后,我该如何做填充实体以便将其保存回来?我通常会这样:
ProductInformation info = new ProductInformation();
info.SomeField1 = val1;
info.SomeField2 = val2;
ctx.ProductInformation.InsertOnSubmit( info );
ctx.SubmitChanges();
但是当没有这样的事情时,如何使用上面相同的列集合来填充列,同时迭代它:
info["field1"].Value = val1;
谢谢。
I can get column list from the table using LINQ like this:
OrderDataContext ctx = new OrderDataContext();
var cols = ctx.Mapping.MappingSource
.GetModel( typeof( OrderDataContext ) )
.GetMetaType( typeof( ProductInformation ) )
.DataMembers;
This gives me the list of columns, so I can do this:
foreach ( var col in cols )
{
// Get the value of this column from another table
GetPositionForThisField( col.Name );
}
So this all works, I can iterate through column list and pull the values for those columns from an another table (since the column names are the keys in that another table), so I don't have to do switch....or lot of if...then...
Now the question:
After I get these values, how do I populate the entity in order to save it back? I would normally go like this:
ProductInformation info = new ProductInformation();
info.SomeField1 = val1;
info.SomeField2 = val2;
ctx.ProductInformation.InsertOnSubmit( info );
ctx.SubmitChanges();
But how to use the same column collection from above to populate the columns while iterating over that, when there is no such thing as:
info["field1"].Value = val1;
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需获取您想要修改的对象,设置属性并调用 SubmitChanges。无需创建新对象并插入它。上下文会跟踪您更改的属性并相应地生成更新语句。在您的情况下,您可能希望通过反射而不是手动设置属性,因为您是从另一个表读取它们。
Just fetch the object that you want to modofy, set the property and call SubmitChanges. There is no need to create a new object and insert it. The Context tracks your changed properties and generates the update statement accordingly. In your case you may want to set the properties via reflection rather than manually since you are reading them from another table.
您需要使用反射。假设您可以从元数据中获取
PropertyInfo
:You'll need to use reflection. Assuming you can get the
PropertyInfo
from the metadata: