【问题标题】:Cannot update entity using extension of DbSet无法使用 DbSet 的扩展更新实体
【发布时间】:2015-10-08 16:09:11
【问题描述】:

我在使用实体框架更新数据库时遇到问题。当方法 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"/>-->

【问题讨论】:

  • 因为this.Configuration.AutoDetectChangesEnabled被设置为false;

标签: c# entity-framework repository-pattern


【解决方案1】:

如果你改变了

this.Configuration.AutoDetectChangesEnabled = false;

this.Configuration.AutoDetectChangesEnabled = true;

实际上,您是在告诉 EF 不要跟踪更改,因此状态将始终保持不变。

如果你想关闭它,你可以像这样手动将它添加到跟踪器中

this.m_context.Entry(entity).State = EntityState.Added; //or EntityState.Modified

【讨论】:

    猜你喜欢
    • 2014-04-28
    • 1970-01-01
    • 1970-01-01
    • 2012-11-11
    • 2016-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-26
    相关资源
    最近更新 更多