运行存储过程后刷新存储库

Rom*_*syk 5 .net c# asp.net-mvc entity-framework asp.net-web-api

我在我的WebAPI项目中执行以下操作,该项目运行存储过程以更新(以及其他一些操作)People表:

public HttpResponseMessage SetAsMain(int id)
{
    People people = repository.GetById(id);

    if (people == null)
    {
        return ErrorMsg(HttpStatusCode.NotFound, string.Format("No people with ID = {1}", id));
    }

    if (people.IsMain)
    {
        return ReturnMsg(HttpStatusCode.OK, string.Format("{0} is already set as main", people.FullName)); 
    }

    try
    {
        var parameters = new Dictionary<string, string>();
        parameters.Add("PeopleID", id.ToString());                

        repository.ExecProcedure("usp_PeopleSetMain", parameters);
        return Request.CreateResponse(HttpStatusCode.OK, repository.GetById(id)); 
    }
    catch (Exception ex)
    {
        return ErrorMsg(HttpStatusCode.InternalServerError, ex.Message);
    }
}
Run Code Online (Sandbox Code Playgroud)

我在使用存储过程更新后检索数据时遇到问题.在这个地方:

return Request.CreateResponse(HttpStatusCode.OK, repository.GetById(id));
Run Code Online (Sandbox Code Playgroud)

我得到的数据与更新前的数据相同.但是当我再次调用这个方法时,会有一个实际的数据.

如何刷新存储库中的数据?

你能告诉我为什么repository.GetById(id)从来没有取过新的数据ExecProcedure.如果我需要添加更多信息,请告诉我


我的存储库中的UPDATE方法GetById:

public T GetById(object id)
{
   return context.Set<T>().Find(id);
}
Run Code Online (Sandbox Code Playgroud)

And*_*rei 7

之所以会发生这种情况,是因为实体框架上下文已包含 方法Find(id)始终检查上下文中是否存在对象,如果存在,Entity Framework将不会查询数据库.存储过程不会更改上下文对象,因为它们是直接针对数据库执行的,这就是您在实体中看不到更新值的原因.

您可以使用以下某项内容解决此问题:

  1. 在上下文中停止实体跟踪
  2. 使用AsNoTracking()查询实体不遵循跟踪.
  3. 查询对象使用First(...),FirstOrDefault(...),Single(...)等执行存储过程之后.

我建议你选择选项1或2.选项1:

context.Entry(people).State = EntityState.Detached;
Run Code Online (Sandbox Code Playgroud)

如果您运行早期版本的Entity Framework,则应该分离对象:

context.People.Detach(people);
Run Code Online (Sandbox Code Playgroud)

(感谢ieaglle)您还可以查询您的实体立即关闭跟踪(选项2):

context.People.AsNoTracking().FirstOrDefault(p => p.Id == id);
Run Code Online (Sandbox Code Playgroud)

  • `AsNoTracking` IMO更好,因为它首先不会将实体附加到上下文.在你的例子中,'yourEntity`将在你的行之前附上. (2认同)