从覆盖的SaveChanges()更新属性
本文关键字:更新 属性 SaveChanges 覆盖 | 更新日期: 2023-09-27 18:04:15
我需要重写SaveChanges(),以便在某些实体被修改时更新列(NewClub.LastActivityDate)。问题是,很多时候具有LastActivityDate的表(NewClub)不在呈现给SaveChanges()的实体集中,因此我需要一种方法来更新NewClub。LastActivityDate是否在实体集中
这是我到目前为止写的。
Thanks for looking
public override int SaveChanges()
{
var saveSuccess = false;
var newClubPrimaryKeyId = 0;
ObjectContext ctx = ((IObjectContextAdapter)this).ObjectContext;
List<ObjectStateEntry> objectStateEntryList =
ctx.ObjectStateManager.GetObjectStateEntries(EntityState.Added
| EntityState.Unchanged // need this to get to NewClub when it's not the table being updated
| EntityState.Modified
| EntityState.Deleted).ToList();
foreach (ObjectStateEntry entry in objectStateEntryList)
{
//Skip over relationships
if (entry.IsRelationship) continue;
//Make sure the entity is a member of the NCO schema: NewClub[...]
if (SecurityHelper.IsValidNewClubTableName(entry.EntitySet.Name))
{
entityInfoStr += "Entity Name: " + entry.EntitySet.Name + " Entity State: " + entry.State;
var nc = entry.Entity as NewClub;
var ncp = entry.Entity as NewClubProspect;
if (nc != null) { newClubPrimaryKeyId = nc.Id; }
else if (ncp != null){newClubPrimaryKeyId = ncp.NewClubId;}
//... More comparisons here....
//---------------------------------------------------------------
//Update NewClub.LastActivityDate where Id == newClubPrimaryKeyId
//----------------------------------------------------------------
//This does not work
string q = @"UPDATE NewClub SET LastActivityDate=" + DateTime.Now + " WHERE Id=" +
newClubPrimaryKeyId;
var t = ctx.CreateQuery<NewClub>(q);
}
}
try
{
saveSuccess = base.SaveChanges() > 0;
}
catch (Exception e)
{
string ex = e.ToString();
}
return saveSuccess ? 1 : 0;
}
您不需要为此手动编写SQL查询,条目对象允许您访问对象的当前和最后状态。
试试这样
foreach( var entry in objectStateEntryList)
{
var lastTime = entry.Property("LastActivityDate");
if(lastTime != null)
{
lastTime.CurrentValue = DateTime.Now;
lastTime.IsModified = true; // be careful with this, throws exception if object is added not modified
}
}
你可能还想看看EFHooks https://github.com/visoft/EFHooks