DateCreated and DateModified in ASP.NET MVC 5

℡╲_俬逩灬. 提交于 2019-12-19 09:32:01

问题


I am working on a Code-First project, and I need database to handle DateCreated and DateModified.

The application is running on IIS Express with LocalDB on dev machine, and will be using SQL Server 2012 on deployment server with IIS 7.5.

I have the following model:

public class Person : IdentityUser {

  [Required]
  public string Name { get; set; }

  public Date DateOfBirth { get; set; }

  public string Address { get; set; }

  [DatabaseGeneratedOption.Identity]
  public Date DateCreated { get; set; }

  [DatabaseGeneratedOption.Identity]
  public Date DateModified { get; set; }

}

Please lay out exact steps to configure DB to handle the transaction meta dates, like what needs to be set in model and if there are any actions to be taken in DB context configurator. I was searching for something like: "All you need to know about ASP.NET MVC date handling", but couldn't much touching that aspect.

Thanks in advance.


回答1:


I will think about this from the Entity-framework Point of view.

You basically need to do the following :

1- I will define an interface like ITrackable interface, and make my models implement that interface if these models need track the DateCreated and DateModified porperties.

2- Somehow your model know whether it is am Added/Modified entities because this will decide which property to set (Both for Added entity and just DateModified for Modified entities).

3- With your DbContext in Entity-Framework Add an extension method that you need to call when you try to save your entities through SaveChanges or SaveChangesAsync and this method will loop through the tracked entities and set the DateCreated and DateModified properties according to the entity's state.

So your model will look like this:

public class Person : IdentityUser, ITrackable
{

    [Required]
    public string Name { get; set; }

    public Date DateOfBirth { get; set; }

    public string Address { get; set; }

    public DateTime DateCreated { get; set; }

    public DateTime DateModified { get; set; }
}

Where ITrackable looks like

public interface ITrackable
{
    public DateTime DateCreated { get; set; }

    public DateTime DateModified { get; set; }
}

and the extension method will be something like this:

internal static class ContextHelper
{
    internal static void SyncObjectsStatePreCommit(this DbContext dbContext)
    {
        foreach (var dbEntityEntry in dbContext.ChangeTracker.Entries())
        {

            // do any other stuff you want.
            // ..
            // ..

            // work with ITrackable entities
            var trackableObject = dbEntityEntry.Entity as ITrackable;

            // we need to set/update trackable properties
            if (trackableObject == null)
            {
                continue;
            }

            var dateTime = DateTime.Now;

            // set createddate only for added entities
            if (entityState.ObjectState == ObjectState.Added)
            {
                trackableObject.CreatedDate = dateTime;
            }

            // set LastUpdatedDate for any case other than Unchanged
            if (entityState.ObjectState != ObjectState.Unchanged)
            {
                trackableObject.ModifiedDate = dateTime;
            }
        }
    }
}

Now in your dbContext Save method for example you need to call this method to setup all these properties.

public override Task<int> SaveChangesAsync()
{
    this.SyncObjectsStatePreCommit();
    return base.SaveChangesAsync();
}

Hope that helps.




回答2:


I found the above answer a bit confusing, however i think a more straight forward solution would be to override the SaveChanges method as described in this blog

This solution also uses the ITrackable interface and when SaveChanges is fired it checks whether an Entity implements this interface:

public override System.Threading.Tasks.Task<int> SaveChangesAsync()
{
    foreach (var auditableEntity in ChangeTracker.Entries<ITrackableEntity>())
    {
        if (auditableEntity.State == EntityState.Added ||
            auditableEntity.State == EntityState.Modified)
        {
            // implementation may change based on the useage scenario, this
            // sample is for forma authentication.
            string currentUser = HttpContext.Current.User.Identity.GetUserId();
            DateTime currentDate = SiteHelper.GetCurrentDate();

            // modify updated date and updated by column for 
            // adds of updates.
            auditableEntity.Entity.ModifiedDateTime = currentDate;
            auditableEntity.Entity.ModifiedUserId = currentUser;

            // pupulate created date and created by columns for
            // newly added record.
            if (auditableEntity.State == EntityState.Added)
            {
                auditableEntity.Entity.CreatedDateTime = currentDate;
                auditableEntity.Entity.CreatedUserId = currentUser;
            }
            else
            {
                // we also want to make sure that code is not inadvertly
                // modifying created date and created by columns 
                auditableEntity.Property(p => p.CreatedDateTime).IsModified = false;
                auditableEntity.Property(p => p.CreatedUserId).IsModified = false;
            }
        }
    }
    return base.SaveChangesAsync();
}


来源:https://stackoverflow.com/questions/27221137/datecreated-and-datemodified-in-asp-net-mvc-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!