[英]Entity Framework get user from contex in saveChanges
我的解決方案中有兩個項目,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;
}
}
但是如何在這里獲取用戶名? 我不能使用任何httpContex getUser,因為這是類項目。 有任何想法嗎?
這是我的重點
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IDbContext
所以我想通過另一個字段LogedUserName擴展ApplicationUser,並在用戶登錄時填充它,但是如何在SaveChanges方法中獲取此字段?
如果您確定此類類庫將始終在ASP.NET管道中使用,則實際上可以訪問HttpContext
。 您需要在System.Web
中引用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
是擁有當前用戶的控制器屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.