[英]MVC tracking fields such as Author and Editor (Created By and Modified By)
我正在尋找跟蹤數據庫中所有實體的“作者”和“編輯者”字段的最佳方法。
我首先創建一個基本模型,所有模型都繼承自該模型:
public class DatabaseEntity
{
[Key]
public int Id { get; set; }
[Display(Name = "Last Modified By")]
public ApplicationUser Editor { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
[Display(Name = "Last Modified")]
public DateTime LastModified { get; set; }
[Display(Name = "Created By")]
public ApplicationUser Creator { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime Created { get; set; }
}
這很好,但是我必須在控制器的每個動作中設置這些字段。 每次更新或編輯數據庫中的項目時,如何設置這些字段? 我知道我可以在DbContext
重寫Add
,但是我不知道如何從DbContext
的HttpContext.Current.User.Identity
獲取ApplicationUser
。 我努力了:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser> {
private readonly UserManager<ApplicationUser> userManager;
private readonly HttpContext httpContext;
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, UserManager<ApplicationUser> userManager, IHttpContextAccessor contextAccessor)
: base(options)
{
this.contextAccessor = contextAccessor;
this.httpContext = contextAccessor.HttpContext;
this.userManager = userManager;
}
public override EntityEntry<TEntity> Add<TEntity>(TEntity entity)
{
DatabaseEntity dbEntity = (entity as DatabaseEntity);
if (dbEntity != null)
{
dbEntity.Created = DateTime.Now;
dbEntity.Creator = await userManager.GetUserAsync(httpContext.User);
}
return base.Add(entity);
}
}
但這會導致錯誤,因為userManager.GetUserAsync(httpContext.User);
需要await
和public override EntityEntry<TEntity> Add<TEntity>(TEntity entity)
不是異步的。
要獲取當前用戶,請勿使用UserManager<ApplicationUser>
。 帶注釋dbEntity.Creator = await userManager.GetUserAsync(httpContext.User);
,則會出現錯誤。檢測到類型為'CoreDb.Data.ApplicationDbContext'的服務的循環依賴關系。 由於您在ApplicationDbContext
訪問UserManager<ApplicationUser>
。
我建議您嘗試通過使用當前用戶名查詢DbSet<ApplicationUser>
來獲取當前用戶。
這是一個簡單的代碼:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
private readonly HttpContext httpContext;
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IHttpContextAccessor contextAccessor)
: base(options)
{
this.httpContext = contextAccessor.HttpContext;
}
public DbSet<ApplicationUser> ApplicationUser { get; set; }
public override EntityEntry<TEntity> Add<TEntity>(TEntity entity)
{
DatabaseEntity dbEntity = (entity as DatabaseEntity);
var userName = httpContext.User.Identity.Name;
if (dbEntity != null)
{
dbEntity.Created = DateTime.Now;
dbEntity.Creator = userName == null ? null : ApplicationUser.Where(user => user.UserName == userName).FirstOrDefault();
}
return base.Add(entity);
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.