实体框架从saveChanges中的上下文中获取用户

时间:2015-02-21 18:21:00

标签: c# entity-framework entity-framework-4 entity-framework-5 entity-framework-6

我在我的解决方案中有两个项目,UI作为mvc,类项目首先是版权模型代码。我的模型中有几个实体,但现在我需要通过新的审计字段扩展它们,我需要保存更改实体的人。 我添加了新界面

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

并尝试以这种方式扩展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;
                        }
                    }

但是如何在这里获取userName?我不能使用任何httpContex getUser,因为这是类项目。有什么想法吗?

这是我的背景

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IDbContext

所以我想通过LogedUserName等其他字段扩展ApplicationUser,并在用户登录时填写它,但是如何在SaveChanges方法中获取此字段?

1 个答案:

答案 0 :(得分:2)

如果您确定此类库将始终在ASP.NET管道中使用,那么您实际上可以访问HttpContext。 您需要在类库中引用System.Web,然后:

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

在这种情况下,HttpContext是静态类,而不是属性。

当然,如果在ASP.NET管道之外使用此类(例如在WPF应用程序,控制台应用程序等中),这将失败。以这种方式做这件事似乎并不干净。但它可能是最快的方式,需要最少的现有代码更改。

另一种方法是将用户名或整个身份传递给负责保存更改的类或直接传递给SaveChanges方法。

一个实现可能如下所示:

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

然后在Controller中(如果直接在MVC控制器中使用上下文):

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

其中User是控制器拥有当前用户的属性。