比较LINQ查询检索的更新之前和之后的对象

时间:2014-08-21 15:48:52

标签: linq linq-to-sql

我正在使用LINQtoSQL,我需要在更新之前和之后比较对象。

在下面的示例中,Student'之前'和Student'curStudent'是相同的,因为它们是由同一查询检索的。

using(DataContext db = new DataContext())
{
   Student before = db.Student.Where(q=>q.id == 1).SingleOrDefault();
   Student curStudent = db.Student.Where(q=>q.id == 1).SingleOrDefault();
   curStudent.Name = "NewName";
   db.SubmitChanges();
}

if(before.Name != curStudent.Name) // this condition will never be true
{
    //do something
}

1 个答案:

答案 0 :(得分:1)

上下文每个键值只保留一个对象,因此一种方法是使用两个单独的上下文:

Student before;
using(DataContext db1 = new DataContext())
{
   before = db.Student.Where(q=>q.id == 1).SingleOrDefault();
}

Student curStudent;
using(DataContext db2 = new DataContext())
{
   curStudent = db.Student.Where(q=>q.id == 1).SingleOrDefault();
   curStudent.Name = "NewName";
   db.SubmitChanges();
}

if(before.Name != curStudent.Name) 
{
    //do something
}

或者,如果您只对名称更改感兴趣,请保留以前的值:

string before;

using(DataContext db = new DataContext())
{
   Student curStudent = db.Student.Where(q=>q.id == 1).SingleOrDefault();
   before = curStudent.Name;   // cache the name
   curStudent.Name = "NewName";
   db.SubmitChanges();
}

if(before != curStudent.Name) 
{
    //do something
}