实体框架(6.1.3)更新未在数据上下文中反映

3

1) 我向上下文添加了一个新实体,并调用_context.SaveChanges()。实体按预期添加

2) 我更新相同的实体并调用_context.SaveChanges(),我立即打断点并检查_context,我的更新反映在实体上,并确实保存到数据库中。

3) 我在代码库中稍后调用_context.Set< T >().ToList(),但更新不会反映在实体上。(此时_context不反映更新的值)

可能的原因是什么?我该怎么解决?任何帮助都将不胜感激

回应代码请求...

从存储库中...

    public List<T> GetAll()
    {
        return _context.Set<T>().ToList();
    }

    public void SaveChanges()
    {
        _context.SaveChanges();

       var xxx = _context.Customers.ToList();
    }

From the call to get all...

    var customersToUpdate = _customerManager.GetAllCustomers();

来自客户经理的...

    public List<Customer> GetAllCustomers()
    {
        return _customerRepository.GetAll();
    }

相当基础的内容。

3
你能展示相关代码部分吗? - Yacoub Massad
2个回答

2

您确定只使用了一个_customerRepository实例吗?并且每次更新_context时,都是在_customerRepository下的同一上下文中进行的吗?听起来像是您有多个实例,其中一个被更新而其他实例没有被更新。


我也曾这样想过,但实际上并不是这样。除非Ninject在做一些我看不到的奇怪事情。 - Trenton

0
基本上,您需要告诉 EF 您进行了更新。最简单的方法是:
var customer = _context.Customers.First();

customer.Name = "new name";

_context.Entry(customer).State = EntityState.Modified; 

_context.SaveChanges();

或者您可以更具体地说明下面的更改内容:

customer.Name = "new name";
context.Entry(customer).Property(u => u.Name).IsModified = true;
_context.SaveChanges();

你可以这样启用自动更改检测
context.Configuration.AutoDetectChangesEnabled = true; 

在这种情况下
  • DbSet.Find
  • DbSet.Local
  • DbSet.Remove
  • DbSet.Add
  • DbSet.Attach
  • DbContext.SaveChanges
  • DbContext.GetValidationErrors
  • DbContext.Entry
  • DbChangeTracker.Entries

所有内容都会自动检测更改。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接