原始查询更改未出现在实体对象c#中

时间:2017-06-05 06:01:03

标签: c# .net entity-framework

我已使用原始查询获取列的更新状态,但在更新后,实体对象中未出现更改:

CDIMDEntities oDB = new CDIMDEntities();
SystemYear oSY = oDB.SystemYears.FirstOrDefault(x => x.Year == Year);
if (oSY != null)
{
    string thsQuery = "UPDATE SystemYears SET  " + Column + " = {0} WHERE Id = {1}";
    oDB.Database.ExecuteSqlCommand(thsQuery, Status, oSY.Id);
    //After this changes appeared in database 
    // But when again when trying get object ,It's showing old values 
    oSY = oDB.SystemYears.FirstOrDefault(x => x.Id == oSY.Id);
    this.SystemYearRep.SaveSystemYear(oSY);
}

2 个答案:

答案 0 :(得分:3)

这是因为实体框架在某种意义上“缓存”实体。当您进行第二次查询时

oSY = oDB.SystemYears.FirstOrDefault(x => x.Id == oSY.Id);

EF 进行数据库查询, 将从数据库接收更新的值。但是,在执行此操作后,它会注意到已经SystemYear已将指定ID附加到上下文(您通过第一个查询oDB.SystemYears.FirstOrDefault(x => x.Year == Year)收到的ID)。因此它将丢弃新实体并将旧实体(已附加,具有旧值)返回给您。要强制EF刷新实体 - 请使用Reload

ctx.Entry(oSY).Reload(); // no need to make second query, will be done for you

或只是使用新鲜的背景。

答案 1 :(得分:0)

您正在对您的数据库执行原始查询,在初始化CDIMDEntities()时,您将看不到该更改。

using(CDIMDEntities oDB = new CDIMDEntities())
{
    SystemYear oSY = oDB.SystemYears.FirstOrDefault(x => x.Year == Year);
    if (oSY != null)
    {
        string thsQuery = "UPDATE SystemYears SET  " + Column + " = {0} WHERE Id = {1}";
        oDB.Database.ExecuteSqlCommand(thsQuery, Status, oSY.Id);

        // Your raw query will not affect the SystemYears at this point.
        oSY = oDB.SystemYears.FirstOrDefault(x => x.Id == oSY.Id);

        // This does nothing at this point.
        this.SystemYearRep.SaveSystemYear(oSY);
    }
}

// New up a another context
using(var CDIMDEntities oDB2 = new CDIMDEntities())
{
   // You will see the changes here
   SystemYear oSY = oDB2.SystemYears.FirstOrDefault(x => x.Year == Year);
}

使用DbContext关键字升级using时的一个好习惯,因为它有助于在使用后处理上下文。