从重写的SaveChanges()更新属性

时间:2014-05-19 13:02:58

标签: c# asp.net-mvc-3 entity-framework

我需要覆盖SaveChanges(),以便在修改某些实体时更新列(NewClub.LastActivityDate)。问题是很多次具有LastActivityDate的表(NewClub)不在实体集中呈现给SaveChanges()所以我需要一种方法来更新NewClub.LastActivityDate(如果它在实体集中)。 / p>

这是我到目前为止所拥有的。

感谢您寻找

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; 
        }   

1 个答案:

答案 0 :(得分: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