我正在寻找跟踪数据库中所有实体的作者和编辑器字段的最佳方法。
我首先创建了一个我所有模型都继承自的基础模型:
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; }
}
这很好用,但我必须在控制器的每个动作中设置这些字段。每次更新或编辑数据库中的项目时,如何设置这些字段?我知道我可以覆盖Add
中的DbContext
,但我不知道如何从ApplicationUser
HttpContext.Current.User.Identity
中获取DbContext
。我试过了:
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)
不是异步。
答案 0 :(得分:2)
要获取当前用户,您不应使用toFixed(2)
。通过评论UserManager<ApplicationUser>
,您将收到错误检测到类型&#39; CoreDb.Data.ApplicationDbContext&#39;。的服务的循环依赖关系,因为您访问{{1在dbEntity.Creator = await userManager.GetUserAsync(httpContext.User);
中。
我建议您尝试通过使用当前用户名查询UserManager<ApplicationUser>
来获取当前用户。
这是一个简单的代码:
ApplicationDbContext