c# - 将对数据库所做的更改存储在 Entity Framework 中

标签 c# sql-server entity-framework linq

我想将对数据库所做的更改存储在结构或其他东西中,以便我可以在数据库上下文结束后随时引用它们。我在 C# 中使用 Entity Framework ,在 SQL Server 中使用底层数据库。

我要存储的信息是

  • 执行数据库上下文
  • 表名
  • 更新列的先前值
  • 更新列的新值
  • 添加或删除的行的 ID。
  • 执行的操作(更新或删除或添加)

目前我以字符串的形式存储它们。但问题是,使用这种方法我无法重现 linq 查询,以便我可以恢复更改。

在这种情况下我该怎么办?提前致谢。

最佳答案

您可以观察change tracker之前SaveChanges ,并将更改存储在您自己的模型中。稍后,使用该模型来回放反转 Action 。

例如,鉴于此上下文:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class SampleContext : DbContext
{
    public DbSet<Person> People { get; set; }
}

你可以写这样一个类:

public class SampleContextMemento
{
    private IEnumerable<Person> addedPeople;
    private IEnumerable<Person> deletedPeople;

    private IEnumerable<T> GetEntitiesByState<T>(SampleContext context, EntityState state)
        where T : class
    {
        return context.ChangeTracker
            .Entries<T>()
            .Where(_ => _.State == state)
            .Select(_ => _.Entity)
            .ToList();
    }

    public void RecordChanges(SampleContext context)
    {
        addedPeople = GetEntitiesByState<Person>(context, EntityState.Added);
        deletedPeople = GetEntitiesByState<Person>(context, EntityState.Deleted);
    }

    public void RollbackChanges(SampleContext context)
    {
        // delete added entities
        if (addedPeople != null)
        {
            foreach (var item in addedPeople)
            {
                context.People.Remove(context.People.Find(item.Id));
            }
        }

        if (deletedPeople != null)
        {
            // add deleted entities
            foreach (var item in deletedPeople)
            {
                context.People.Add(item);
            }
        }

        // save reverted changes
        context.SaveChanges();
    }
}

并像这样使用它:

var memento = new SampleContextMemento();

// make changes
using (var context = new SampleContext())
{
    // add some entities
    context.People.Add(new Person { Id = 100, Name = "John" });
    // remove some
    context.People.Remove(context.People.Find(1));
    // saving changes in our memento to rollback them later
    memento.RecordChanges(context);
    context.SaveChanges();
}

// rollback them
using (var context = new SampleContext())
{
    memento.RollbackChanges(context);
}

当然,通用解决方案会更复杂,但这应该给您基本的想法。

关于c# - 将对数据库所做的更改存储在 Entity Framework 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35741065/

相关文章:

c# - 在字典内部的字典中添加键值对

c# - ServiceNow 表 API 返回重复项/不返回所有记录

java - 测试 SQL Server 驱动程序是否存在

entity-framework - 急切加载多态子对象属性

c# - 在 LINQ 中获取组的第一条记录?

c# - 数据库设计 : Custom fee/billing charge rates

c# - 使用 C# 在运行时合并两个对象的最佳方法是什么?

sql-server - 当 SSRS 报告包含字符值高于 127 的 Wingdings 时将其导出为 PDF

sql-server - 验证数据库更改(版本控制)

c# - ObjectContext 实例已被处理,不能再使用(ASP.NET MVC)