Spirosi
Spirosi

Reputation: 324

EF tracking changes in database

im using Entity Framework6 in my solution, and now i need to track changes in database but cant figure out how to do it. Is there a way to track changes in database using Entity Framwork?

update: I've found this solution, its using SqlDependency in the way that allows to use it With Entity framework.

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

Upvotes: 2

Views: 1395

Answers (2)

Spirosi
Spirosi

Reputation: 324

I've found this solution, its using SqlDependency in the way that allows to use it With Entity framework.

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

Upvotes: 2

Stephen Reindl
Stephen Reindl

Reputation: 5829

You can overwrite the SaveChanges() method to track the changes. Here's some example out of one of our applications:

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

where SystemFields is a ComplexType added to all entries which implement the IAuditable interface:

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

Upvotes: 1

Related Questions