当“编辑”时一个 LINQ to SQL 实体,我可以简单地将一项分配给另一项吗?
为了清楚起见,假设我有这段代码:
void AlterItem(Orderable o) {
foreach(Orderable p in from Orderable n in dataContext.Orderables
where n.UID == o.UID
select n)
p = o;
dataContext.SubmitChanges();
当然这段代码不起作用,因为你不能分配给迭代变量,这对我来说很清楚。有没有比重写特定字段更好的方法?我尝试了 Single() 但将一个变量分配给另一个变量后,它不会应用更改。
抱歉,如果之前有人问过这个问题。我努力寻找答案,但失败了。
To be clear, let's say I have this code:
void AlterItem(Orderable o) {
foreach(Orderable p in from Orderable n in dataContext.Orderables
where n.UID == o.UID
select n)
p = o;
dataContext.SubmitChanges();
Of course this code does not work, because you cannot assign to an iterational variable, this is clear for me. Is there any way better than rewriting particular fields? I tried Single() but after assigning one variable to another it does not apply changes.
Sorry if this was asked before. I did my efforts to find the answer and failed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,除了
foreach()
参数问题之外,简单的p = o;
只会复制引用。最好的办法是编写代码来复制属性,也许可以使用 AutoMapper。
No, aside from the
foreach()
parameter problem a simplep = o;
would only copy a reference.The best thing is to write code to copy properties, maybe with the use of AutoMapper.
变量和对象之间似乎存在混淆。在下面的代码中,所发生的只是变量
p
引用与o
参数相同的对象,而不是dataContext.Orderables.First( )
。当您提交更改时,实际上不会提交任何内容,因为没有任何数据库对象发生更改。仅更改了引用:为了更改从 dataContext.Orderables.First() 返回的对象,您必须更改其属性。您还可以通过 foreach 变量修改对象,如下所示:
There seems to be a confusion between variables and objects. With the following, all that happens is that the variable
p
refers to the same object as theo
parameter instead of the return object fromdataContext.Orderables.First()
. When you submit changes, nothing is actually submitted because none of the database objects were changed. Only a reference was changed:In order to change the object returned from
dataContext.Orderables.First()
you have to change its properties. You can also modify the object via aforeach
variable this way: