[英]How do i replace a linq object from a method call
I have a linq object that I'd like to "retire" when certain aspects are changed and the Save()
method is called.我有一个 linq object,当某些方面发生更改并调用
Save()
方法时,我想“退休”。 The database does this by having a Terminated column which when set causes the object to be ignored on subsequent queries.数据库通过设置一个 Terminated 列来做到这一点,该列在设置时会导致 object 在后续查询中被忽略。 I'd like to do this transparently so for example:
我想透明地做到这一点,例如:
DataContext db = new DataContext();
Foo bar = (from a in db.table
where a.pk == somevalue
select a).Single();
bar.Price += 2;
Console.WriteLine(bar.pk);
bar.Save();
Console.WriteLine(bar.pk);
The second WriteLine()
should be a different key than the first because in the process of saving I've created a duplicate object and replaced bar with it.第二个
WriteLine()
应该是与第一个不同的键,因为在保存过程中我创建了一个重复的 object 并用它替换了 bar 。 Essentially inside the save method I want to set this = newObj;
基本上在保存方法中我想设置
this = newObj;
. . Is what I want possible or am I going about this the wrong way?
我想要的是可能的还是我以错误的方式去做?
You can change references (or more precisely the variables that hold them) if they are passed by reference:如果引用是通过引用传递的,您可以更改引用(或更准确地说是保存它们的变量):
class Foo {
...
public static void Save(ref Foo obj)
{
var newObj = obj._save() //your implementation
obj = newObj;
}
}
There is no other way to change references.没有其他方法可以更改引用。 The reason is, that objects don't know where they are referenced.
原因是,对象不知道它们在哪里被引用。 The Foo object doesn't know about any references to it.
Foo object 不知道对它的任何引用。
If you want the exact behaviour you outlined in your code, the only way to achieve this, is to change the contents of your Foo instance, ie, overwrite each and every field with the updated values.如果您想要代码中概述的确切行为,实现此目的的唯一方法是更改 Foo 实例的内容,即用更新的值覆盖每个字段。
Hope this helps.希望这可以帮助。
An alternative would be to return the new object from the Save() method;另一种方法是从 Save() 方法返回新的 object; This probably makes more sense if the Save() method is not part of the object.
如果 Save() 方法不是 object 的一部分,这可能更有意义。 So for example:
例如:
var dataPersister = new DataPersister();
var obj = dataPersister.Load(somevalue);
obj.Price += 2;
var newObj = dataPersister.Save(obj);
After those calls, obj would still point at the original object, newObj would be the result after saving.在这些调用之后,obj 仍将指向原始的 object,newObj 将是保存后的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.