我正在使用EF6和Asp.Net身份验证构建一个项目。
我遇到了以下问题:
如果我调用
var account = await FindByNameAsync(userName); // account.IsConfirmed = true
我获取了我要查找的账户(例如:isConfirmed=true)。
当我手动修改数据库中的值(isConfirmed=true -> isConfirmed=false),再次运行查询时,我仍然得到旧的账户对象(isConfirmed=true)。
var account = await FindByNameAsync(userName); // Should be account.IsConfirmed = false, but still gives me IsConfirmed = true
我尝试在我的DbContext构造函数中添加以下内容
> this.Configuration.ProxyCreationEnabled = false;
> this.Configuration.LazyLoadingEnabled = false;
但这并没有改变任何事情。
我该怎么办呢?缓存数据的保留时间有多长? 所有我看到的帖子都要求你运行查询(从..中..),但是考虑到我正在使用aspnet Identity,并且我无法控制这些内容,我该怎么办呢?
谢谢!
编辑:添加了dbContext信息
我的IoC(Unity)
container.RegisterType<IUnitOfWork, UserManagementContext>(new HttpContextLifetimeManager<IUnitOfWork>());
container.RegisterType<IUserStore<Account>, UserStore<Account>>(new InjectionConstructor(container.Resolve<IUnitOfWork>()));
HttpContextLifeTimeManager:
public class HttpContextLifetimeManager<T> : LifetimeManager, IDisposable
{
public override object GetValue()
{
return HttpContext.Current.Items[typeof(T).AssemblyQualifiedName];
}
public override void SetValue(object newValue)
{
HttpContext.Current.Items[typeof(T).AssemblyQualifiedName] = newValue;
}
public override void RemoveValue()
{
HttpContext.Current.Items.Remove(typeof(T).AssemblyQualifiedName);
}
public void Dispose()
{
RemoveValue();
}
}
我的 IUnitOfWork
public interface IUnitOfWork : IDisposable
{
void Save();
Task SaveAsync();
DbSet<TEntity> EntitySet<TEntity>() where TEntity : class;
void MarkAsModified<TEntity>(TEntity entity) where TEntity : class;
}
我的用户管理上下文
public class UserManagementContext : IdentityDbContext<Account>, IUnitOfWork
{
static UserManagementContext()
{
//Database.SetInitializer<UserManagementContext>(new RecreateDatabase());
Database.SetInitializer<UserManagementContext>(null);
}
public UserManagementContext()
: base("Name=UserManagementConnection")
{
this.Configuration.ProxyCreationEnabled = false;
this.Configuration.LazyLoadingEnabled = false;
}
// ... (my Dbsets)
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// configuration ..
}
public void Save()
{
SaveChanges();
}
public async Task SaveAsync()
{
await SaveChangesAsync();
}
public DbSet<TEntity> EntitySet<TEntity>() where TEntity : class
{
return this.Set<TEntity>();
}
public void MarkAsModified<TEntity>(TEntity entity) where TEntity : class
{
this.Entry(entity).State = EntityState.Modified;
}
}
更新:
我发现了另一件奇怪的事情。当我设置我的最后登录日期字段时,该更改被捕捉到了,但是当我设置我的isConfirmed字段时,却没有被捕捉到..(实际上,DB更改被缓存数据覆盖了!)
因此,这证实了通过代码输入的数据会被持久化,但是在数据库中进行的手动更改会被忽略。
更新2:
如果有人也遇到这个问题:问题不在于aspnet Identity,而是EF。
我的做法是实现自己的userstore,并手动访问EF并使用.AsNoTracking()来避免缓存。