c# - Entity Framework 从 saveChanges 中的上下文获取用户

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

我的解决方案中有两个项目,作为 mvc 的 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; }
}

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

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

这是我的背景

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IDbContext

所以我想通过另一个字段(如 LogedUserName)扩展 ApplicationUser,并在用户登录时填充它,但是如何在我的 SaveChanges 方法中获取该字段?

最佳答案

如果您确定该类库将始终在 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 Controller 中使用上下文):

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

User 是 Controller 的当前用户属性。

关于c# - Entity Framework 从 saveChanges 中的上下文获取用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28649510/

相关文章:

C# Forms TextBox 选择带有插入符号位置的文本

c# - 将 Entity Framework 与存档数据库一起使用

sql - Entity Framework 数据库查询非常慢

c# - IDbSet<T> 上没有 FindAsync() 方法

entity-framework - 列名无效

c# - 以 Windows 形式播放 youtube 视频

c# - 将 c# int 连接成 .jpg

entity-framework - 使用Linq To Entities中的多列联接表

c# - 在我们的解决方案中将 Entity Framework 放在哪里?

c# - MySqlConnection = new MySqlConnection(string) 不起作用