我们已经覆盖了SaveChanges方法,因为我们想在保存时自动设置一些最终属性,我们必须在每个连接中设置SETCONTEXT。我们当前的覆盖如下:
public override int SaveChanges()
{
// Use basic SaveChanges if SessionInfo is not initialized
if (SessionInfo.ContextInfo == null)
{
return base.SaveChanges();
}
// SessionInfo was initialized, so use custom logic now
// Set the SqlId according to sessioninfo for each entity to add
foreach (DbEntityEntry entry in ChangeTracker.Entries()
.Where(x => x.State == EntityState.Added))
{
string sqlIdPropertyName =
entry.CurrentValues.PropertyNames.First(x=>x.EndsWith("SqlId");
entry.Property(sqlIdPropertyName).CurrentValue = SessionInfo.ServerSqlId;
}
// Set the IsDeleted boolean to true for each entity to delete
foreach (DbEntityEntry entry in ChangeTracker.Entries()
.Where(x => x.State == EntityState.Deleted))
{
entry.Property("IsDeleted").CurrentValue = true;
entry.State = EntityState.Modified;
}
// Begin custom transaction if SessionInfo was set
this.Database.Connection.Open();
SessionInfo.SetContextInfo(this);
int result = base.SaveChanges();
this.Database.Connection.Close();
return result;
}
如您所见,当我们向数据库添加新记录时,保存逻辑会根据SessionInfo为对象设置SqlId。但是,这现在取决于PropertyNames.First(),这是一种风险。
我们想要设置的SqlId的PropertyName总是等于POCO类类型+ SqlId的名称,因此对于类" Invoice"它将是" InvoiceSqlId"。
我们如何从DbEntityEntry获取原始POCO类的类型名称?
答案 0 :(得分:0)
试试这个:entry.Entity.GetType().Name
编辑 - 适用于您使用代理的时间
var entityType = entry.Entity.GetType();
string name;
if (entityType.BaseType != null &&
entityType.Namespace == "System.Data.Entity.DynamicProxies")
{
name = entityType.BaseType.Name;
}
else
{
name = entityType.Name
}