EF跟踪数据库中的更改

时间:2015-03-04 11:51:31

标签: c# entity-framework

我在我的解决方案中使用Entity Framework6,现在我需要跟踪数据库中的更改,但无法弄清楚如何做到这一点。 有没有办法使用Entity Framwork跟踪数据库中的更改?

更新 : 我已经找到了这个解决方案,它使用SqlDependency的方式允许它与Entity框架一起使用。

http://www.codeproject.com/Articles/233770/AutoRefresh-Entity-Framework-data-using-SQL-Server

2 个答案:

答案 0 :(得分:1)

您可以覆盖SaveChanges()方法来跟踪更改。以下是我们的一个应用程序中的一些示例:

public override int SaveChanges()
{
    ChangeTracker.DetectChanges();
    var entries = ChangeTracker.Entries<IAuditable>();
    if (entries != null)
    {
        foreach (DbEntityEntry<IAuditable> entry in entries)
        {
            switch (entry.State)
            {
                case EntityState.Added:
                    entry.Entity.SystemFields = new SystemFields
                    {
                        SysActivityCode = ActivityCode,
                        SysCreationUser = UserId,
                        SysCreationDate = DateTime.UtcNow
                    };
                    break;
                case EntityState.Modified:
                    entry.Entity.SystemFields.SysModificationDate = DateTime.UtcNow;
                    entry.Entity.SystemFields.SysModificationUser = UserId;
                    entry.Entity.SystemFields.SysActivityCode = ActivityCode;
                    break;
            }
        }
    }

    return base.SaveChanges();
}

其中SystemFieldsComplexType添加到实现IAuditable接口的所有条目中:

public interface IAuditable
{
    /// <summary>
    /// System fields who contain change and status information
    /// </summary>
    SystemFields SystemFields { get; set; }
}

[ComplexType]
public class SystemFields
{
    /// <summary>
    /// When has this entry be created
    /// </summary>
    [Required]
    public DateTime SysCreationDate { get; set; }
    /// <summary>
    /// Who has created the entry
    /// </summary>
    [Required]
    public string SysCreationUser { get; set; }
    /// <summary>
    /// When has this entry been modified
    /// </summary>
    public DateTime? SysModificationDate { get; set; }
    /// <summary>
    /// Who has updated the entry
    /// </summary>
    [CanBeNull]
    public string SysModificationUser { get; set; }
    /// <summary>
    /// Which activity has created/changed this entry
    /// </summary>
    [Required]
    [StringLength(32)]
    public string SysActivityCode { get; set; }
}

答案 1 :(得分:0)

我找到了这个解决方案,它使用SqlDependency的方式允许它与Entity框架一起使用。

http://www.codeproject.com/Articles/233770/AutoRefresh-Entity-Framework-data-using-SQL-Server