Entity Framework get user from contex in saveChanges

c# entity-framework entity-framework-4 entity-framework-5 entity-framework-6

Question

I have two projects in my solution: a class project for entity model code initially and a UI as mvc project. I already have a number of entities in my model, but I now need to add new audit fields so I can save who altered an entity. I upgraded the UI.

public interface IAuditable
{
    /// <summary>Gets or sets the name.</summary>
    /// <value>The name.</value>
    DateTime CreatedDate { get; set; }

    /// <summary>Gets or sets the name.</summary>
    /// <value>The name.</value>
    string CreatedBy { get; set; }

    /// <summary>Gets or sets the name.</summary>
    /// <value>The name.</value>
    DateTime UpdatedDate { get; set; }

    /// <summary>Gets or sets the name.</summary>
    /// <value>The name.</value>
    string UpdatedBy { get; set; }
}

then attempt to add this extension to SaveChanges

foreach (var auditableEntity in ChangeTracker.Entries<IAuditable>())
                {
                    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 = ; 

                        // modify updated date and updated by column for 
                        // adds of updates.
                        auditableEntity.Entity.UpdatedDate = DateTime.Now;
                        auditableEntity.Entity.UpdatedBy = 

                        // pupulate created date and created by columns for
                        // newly added record.
                        if (auditableEntity.State == EntityState.Added)
                        {
                            auditableEntity.Entity.CreatedDate = DateTime.Now;
                            auditableEntity.Entity.CreatedBy = currentUser;
                        }
                        else
                        {
                            auditableEntity.Property(p => p.CreatedDate).IsModified = false;
                            auditableEntity.Property(p => p.CreatedBy).IsModified = false;
                        }
                    }

but how can I obtain the userName in this case? Because this is a project for class, I am unable to utilize any httpContex getUser. Any thoughts?

this is my situation

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IDbContext

I therefore considered adding a field like LoggedUserName to extend ApplicationUser and fill it when a user logs in, but how can I retrieve this field in my SaveChanges method?

1
2
2/21/2015 10:20:37 PM

Popular Answer

You can access this class library if you are certain that it will always be used in the ASP.NET pipeline.HttpContext You require a reference forSystem.Web in the classroom library, after which:

using System.Web;
[...]
public void SaveChanges()
{
    var username = HttpContext.Current.User.Identity.Name;
}

Given this,HttpContext is not a property, but a static class.

Of course, if this class is ever utilized outside of the ASP.NET pipeline, it will fail miserably (for example in WPF application, console app etc). Additionally, doing it this way doesn't seem clean. Though it probably takes the least amount of existing code modification.

A different approach would be to give either the username or the entire identity to the class in charge of saving modifications or to the person.SaveChanges method.

One instance might resemble this:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IDbContext
{
    private IPrincipal _currentUser;
    public ApplicationDbContext(IPrincipal currentUser)
    {
        _currentUser = currentUser;
    }
}

and following that in the Controller (assuming MVC controllers directly use context):

using(var db = new ApplicationDbContext(User))
{
    [...]
}

where User is the current holder of the controller's property.

2
2/22/2015 11:01:25 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow