我通常通過繼承和覆蓋來實現SaveChanges() - 這與Code First一起工作,並且必須手動將審計字段添加到每個類。
public abstract class TrackedEntity
{
public DateTime CreatedDate { get; set; }
public DateTime ModifiedDate { get; set; }
public string ModifiedBy { get; set; }
}
public class SomeOtherClass : TrackedEntity
{
// Class specific properties here
}
,然後在你的DbContext
private User _loggedOnUser
public override int SaveChanges()
{
var timestamp = DateTime.Now;
// First look at new items these need created date adding
var addedEntities = ChangeTracker.Entries().Where(x => x.State == EntityState.Added).Select(x => x.Entity);
foreach (var addition in addedEntities)
{
var entity = addition as TrackedEntity;
if (entity != null)
{
entity.CreatedDate = timestamp;
entity.ModifiedDate = timestamp;
entity.ModifiedBy = _loggedOnUser;
}
}
// Next look at modified entries
var modifiedEntities = ChangeTracker.Entries().Where(x => x.State == EntityState.Modified || x.State == EntityState.Deleted);
foreach (var update in modifiedEntities)
{
// Only check tracked entities if modified
if (update.State == EntityState.Modified)
{
var tracked = update.Entity as TrackedEntity;
if (tracked != null)
{
tracked.ModifiedDate = timestamp;
tracked.ModifiedBy = _loggedOnUser;
}
}
}
}
,並得到用戶
private void GetUser()
{
string user = string.Empty;
// if we have an http context, lets try it first
if (System.Web.HttpContext.Current != null)
{
if (System.Web.HttpContext.Current.User.Identity != null && System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
user = System.Web.HttpContext.Current.User.Identity.Name;
}
if (user == null)
user = System.Threading.Thread.CurrentPrincipal.Identity.Name;
_loggedOnUser = this.Users.SingleOrDefault(x => x.Username == user);
}
這隻有在您使用AD連接到SQL Server實例時才能起作用,然後您可以插入他們的SQL Server關聯ID或AD用戶名。這將在觸發器中可用,因爲您無法將信息傳遞給觸發器。 – Igor
正在搜索CURRENT_USER? https://msdn.microsoft.com/zh-cn/library/ms176050.aspx?f=255&MSPPError=-2147217396 – tym32167
@ tym32167,CURRENT_USER或USER_NAME(USER_ID())從Connection字符串返回用戶。 我需要從我的表用戶有一個用戶,這意味着我需要把他放在我的DbContext的某個地方。但是哪裏? –