实体框架在saveChanges中从contex获取用户 [英] Entity Framework get user from contex in saveChanges
问题描述
我添加了新界面
public interface IAuditable
{
///< summary> ;获取或设置名称。< / summary>
///< value>名称。< / value>
DateTime CreatedDate {get;组; }
///< summary>获取或设置名称。< / summary>
///< value>名称。< / value>
string CreatedBy {get;组; }
///< summary>获取或设置名称。< / summary>
///< value>名称。< / value>
DateTime UpdatedDate {get;组; }
///< summary>获取或设置名称。< / summary>
///< value>名称。< / value>
string UpdatedBy {get;组;
}
并尝试以这种方式扩展SaveChanges
foreach(ChangeTracker.Entries< IAuditable>()中的var auditableEntity)
{
if(auditableEntity.State == EntityState.Added ||
auditableEntity.State == EntityState.Modified)
{
//实现可能会根据使用情况进行更改,此
//样本用于表单身份验证。
string currentUser =;
//修改更新的日期,并按列更新
//添加更新。
auditableEntity.Entity.UpdatedDate = DateTime.Now;
auditableEntity.Entity.UpdatedBy =
// pupulate创建日期并由
/新添加的记录的列创建。
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,因为这是类项目。任何想法?
这是我的contex
public class ApplicationDbContext: IdentityDbContext< ApplicationUser>,IDbContext
所以我想通过另一个字段(如LogedUserName)扩展ApplicationUser,并填写它当用户登录时,但如何在SaveChanges方法中获取此字段?
如果您确定此类库将始终用于ASP.NET管道,您实际上可以访问 HttpContext的
。
您需要在课程库中引用 System.Web
,然后:
使用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))
{
[。 ..]
}
其中用户
是控制器的属性持有当前用户。
i have two projects in my solution, UI as mvc and class project for entitiy model code first. 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
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. 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 ?
If you are sure that this class library will be always used in ASP.NET pipeline you actually can access HttpContext
.
You need a reference to System.Web
in your class library and then:
using System.Web;
[...]
public void SaveChanges()
{
var username = HttpContext.Current.User.Identity.Name;
}
In this case HttpContext
is a static class, not a property.
Ofcourse this will fail badly if this class is ever used outside ASP.NET pipeline (for example in WPF application, console app etc). 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.
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):
using(var db = new ApplicationDbContext(User))
{
[...]
}
where User
is controller's property holding current user.
这篇关于实体框架在saveChanges中从contex获取用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!