我已重写DBContext中的SaveChanges方法,以便检测具有“创建/更新”信息的表并自动处理更新,如下所示:
public partial class MyContext
{
private readonly ITokenService _tokenService;
public MyContext(ITokenService tokenService, DbContextOptions options) : base(options)
{
_tokenService = tokenService;
}
public override int SaveChanges()
{
var entities = ChangeTracker.Entries().Where(entry => entry.Entity is ITrackingEntities);
foreach (var entityEntry in entities)
{
if (entityEntry.State == EntityState.Added)
{
((ITrackingEntities) entityEntry.Entity).CreatedBy = _tokenService.LoginUserId;
((ITrackingEntities) entityEntry.Entity).CreatedDateUtc = DateTime.UtcNow;
}
((ITrackingEntities) entityEntry.Entity).UpdatedBy = _tokenService.LoginUserId;
((ITrackingEntities) entityEntry.Entity).UpdatedDateUtc = DateTime.UtcNow;
}
return base.SaveChanges();
}
}
但是,每当我编写一些在存储库层中引发异常的EF代码时,异常换行都发生在覆盖的方法SaveChanges()
中,而不是在调用存储库方法中发生,这使调试变得很痛苦在一个方法中多次调用SaveChanges()
。
是否有任何方法可以指示调试器不要中断我覆盖的SaveChanges()
方法中的行,而不会破坏该方法的调用者?
答案 0 :(得分:0)
随着它的发展,我在发布问题5分钟后找到了解决方案。对于任何需要这种功能的人,[System.Diagnostics.DebuggerStepThrough]
属性就是您要寻找的,这样我发布的方法就变成了:
[System.Diagnostics.DebuggerStepThrough]
public override int SaveChanges()
{
var entities = ChangeTracker.Entries().Where(entry => entry.Entity is ITrackingEntities);
foreach (var entityEntry in entities)
{
if (entityEntry.State == EntityState.Added)
{
((ITrackingEntities) entityEntry.Entity).CreatedBy = _tokenService.LoginUserId;
((ITrackingEntities) entityEntry.Entity).CreatedDateUtc = DateTime.UtcNow;
}
((ITrackingEntities) entityEntry.Entity).UpdatedBy = _tokenService.LoginUserId;
((ITrackingEntities) entityEntry.Entity).UpdatedDateUtc = DateTime.UtcNow;
}
return base.SaveChanges();
}
这将使调用者“异常冒泡”,因此您可以更轻松地调试问题。但是,我会谨慎使用此方法,因为该方法现在将报告自定义替代错误。