繁体   English   中英

EF跟踪数据库中的更改

[英]EF tracking changes in database

我在解决方案中使用Entity Framework6,现在我需要跟踪数据库中的更改,但无法弄清楚该怎么做。 有没有一种方法可以使用实体框架跟踪数据库中的更改?

更新 :我发现了此解决方案,它以允许与Entity Framework一起使用的方式使用SqlDependency。

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

您可以覆盖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();
}

其中SystemFields是添加到实现IAuditable接口的所有条目的ComplexType

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; }
}

我找到了这种解决方案,它以允许与Entity Framework一起使用的方式使用SqlDependency。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM