使用实体框架更新数据库时出现问题。当 Update(T x)方法被调用但 SaveChanges()返回0时, m_entities 集已被更改。我进行了调试,实体状态仍然存在不变。这是我的Repository类。
public class Repository<T> : IRepository<T> where T : class
{
private readonly IApplicationDbContext m_context;
internal IDbSet<T> m_entities;
public Repository(IApplicationDbContext m_context)
{
this.m_context = m_context;
this.m_entities = this.m_context.Set<T>();
}
public void Update(T x)
{
this.m_entities.AddOrUpdate(x);
}
public void SaveChanges()
{
this.m_context.SaveChanges();
}
}
DbContext类
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IApplicationDbContext
{
public ApplicationDbContext()
: base("name=DefaultConnection")
{
this.Configuration.AutoDetectChangesEnabled = false;
this.Configuration.ValidateOnSaveEnabled = false;
}
}
连接字符串。
<connectionStrings>
<!--<add providerName="System.Data.SqlClient" name="DefaultConnection" connectionString="Data Source=LWCGRGTG75SJU9M; Initial Catalog=HPDB; MultipleActiveResultSets=true; Integrated Security=False; User Id=sa; Password=123456"/>-->
答案 0 :(得分:1)
如果你改变了
this.Configuration.AutoDetectChangesEnabled = false;
到
this.Configuration.AutoDetectChangesEnabled = true;
实际上,您告诉EF不跟踪更改,因此状态将始终保持不变。
如果您想将其关闭,可以手动将其添加到跟踪器
this.m_context.Entry(entity).State = EntityState.Added; //or EntityState.Modified