当“编辑”时一个 LINQ to SQL 实体,我可以简单地将一项分配给另一项吗?

发布于 2024-11-02 02:53:41 字数 390 浏览 0 评论 0原文

为了清楚起见,假设我有这段代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

负佳期 2024-11-09 02:53:41

不,除了 foreach() 参数问题之外,简单的 p = o; 只会复制引用。

最好的办法是编写代码来复制属性,也许可以使用 AutoMapper。

No, aside from the foreach() parameter problem a simple p = o; would only copy a reference.

The best thing is to write code to copy properties, maybe with the use of AutoMapper.

ゝ偶尔ゞ 2024-11-09 02:53:41

变量和对象之间似乎存在混淆。在下面的代码中,所发生的只是变量 p 引用与 o 参数相同的对象,而不是 dataContext.Orderables.First( )。当您提交更改时,实际上不会提交任何内容,因为没有任何数据库对象发生更改。仅更改了引用:

void AlterItem(Orderable o)
{
   var p = dataContext.Orderables.First();
   p = o;
   dataContext.SubmitChanges();
}

为了更改从 dataContext.Orderables.First() 返回的对象,您必须更改其属性。您还可以通过 foreach 变量修改对象,如下所示:

var p = dataContext.Orderables.First();
p.Property1 = o.Property1;
// etc...
dataContext.SubmitChanges();

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 the o parameter instead of the return object from dataContext.Orderables.First(). When you submit changes, nothing is actually submitted because none of the database objects were changed. Only a reference was changed:

void AlterItem(Orderable o)
{
   var p = dataContext.Orderables.First();
   p = o;
   dataContext.SubmitChanges();
}

In order to change the object returned from dataContext.Orderables.First() you have to change its properties. You can also modify the object via a foreach variable this way:

var p = dataContext.Orderables.First();
p.Property1 = o.Property1;
// etc...
dataContext.SubmitChanges();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文