简体   繁体   English

实体框架从saveChanges中的contex获取用户

[英]Entity Framework get user from contex in saveChanges

i have two projects in my solution, UI as mvc and class project for entitiy model code first. 我的解决方案中有两个项目,UI作为mvc,第一个用于实体模型代码的类项目。 I have severall entities in my model but now I need to extend them by new audit fields where I need to save who changed entity. 我的模型中有多个实体,但是现在我需要通过新的审计字段来扩展它们,并在其中保存谁更改了实体。 I added new interface 我添加了新界面

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

and try to extend SaveChanges in this way 并尝试以这种方式扩展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 do I get the userName here ? 但是如何在这里获取用户名? I can't use any httpContex getUser becuase this is class project. 我不能使用任何httpContex getUser,因为这是类项目。 Any ideas? 有任何想法吗?

this is my contex 这是我的重点

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IDbContext

so I thought to extend ApplicationUser by another field like LogedUserName, and fill it when user is loging, but how do I get this field in my SaveChanges method ? 所以我想通过另一个字段LogedUserName扩展ApplicationUser,并在用户登录时填充它,但是如何在SaveChanges方法中获取此字段?

If you are sure that this class library will be always used in ASP.NET pipeline you actually can access HttpContext . 如果您确定此类类库将始终在ASP.NET管道中使用,则实际上可以访问HttpContext You need a reference to System.Web in your class library and then: 您需要在System.Web中引用System.Web ,然后:

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

In this case HttpContext is a static class, not a property. 在这种情况下, HttpContext是静态类,而不是属性。

Ofcourse this will fail badly if this class is ever used outside ASP.NET pipeline (for example in WPF application, console app etc). 当然,如果在ASP.NET管道之外(例如,在WPF应用程序,控制台应用程序等中)使用此类,则这样做将严重失败。 Also it doesn't seem clean to do it this way. 同样,这样做似乎并不干净。 But it's probably the fastest way which requires minimal existing code change. 但这可能是最快的方法,需要最少的现有代码更改。

Another way would be to pass either username or whole identity to either class responsible for saving changes or directly to SaveChanges method. 另一种方法是将用户名或整个身份传递给负责保存更改的类,或者直接传递给SaveChanges方法。

One implementation could look like this: 一种实现可能如下所示:

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

and then in Controller (if you use context directly in MVC controllers): 然后在Controller中(如果直接在MVC控制器中使用上下文):

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

where User is controller's property holding current user. 其中, User是拥有当前用户的控制器属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM