2014-07-11 165 views
0

我想从DbContext中覆盖方法SaveChanges()以在其中添加一些控件。我的想法是找到所有已修改的对象并重新加载其先前的值以与新的对象进行比较。如何使用类型创建对象

public override int SaveChanges() 
{ 
    IEnumerable<ObjectStateEntry> changes = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.GetObjectStateEntries(EntityState.Modified); // will store a list of all modified items 

    foreach(var change in changes) 
    { 
     string tableName = change.Entity.GetType().Name;  
     Type myType = Type.GetType(change.Entity.GetType().FullName); 
     string itemID = change.CurrentValues.GetValue(0); 

     string request = "select * from dbo."+tableName+" where ID="+ itemID; 
     // the following line does not work 
     var myObj = db.Database.SqlQuery(myType, request, new SqlParameter("p1", "")); 

    } 
} 

myObj类型是DbRawSqlQuery。我无法找到如何创建类型为“myType”的对象,然后查询数据库以找到它。

+1

看看['Activator.CreateInstance'](http://msdn.microsoft.com/en-us/library/system.activator.createinstance%28v=vs.110%29.aspx)。 – sgbj

+0

在讨论你的问题之前,你为什么要这么做? – gustavodidomenico

+0

@gustavodidomenico:我希望能够通过将我的模型与之前的值进行比较来记录我的模型的哪些值已更改。 – SebC

回答

0

,我发现这是解决方案:

public override int SaveChanges() 
{ 
    IEnumerable<ObjectStateEntry> changes = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.GetObjectStateEntries(EntityState.Modified); // will store a list of all modified items 

    foreach(var change in changes) 
    { 
     string tableName = change.Entity.GetType().Name;  
     Type myType = Type.GetType(change.Entity.GetType().FullName); 
     string itemID = change.CurrentValues.GetValue(0); 

     string request = "select * from dbo."+tableName+" where ID="+ itemID; 
     object myObj_4 = db.Database.SqlQuery(myType, request, new SqlParameter("p0", tempID)).Cast<object>().ToList().First(); 
     foreach (PropertyInfo propertyInfo in myType.GetProperties().Where(g=>!g.GetGetMethod().IsVirtual)) 
     { 
      var oldValue = propertyInfo.GetValue(myObj_4) ?? ""; 
      var newValue = propertyInfo.GetValue(changes.First().Entity) ?? ""; 

      if (oldValue.ToString() != newValue.ToString()) 
      { 
       //Log the diferences between object 
      } 
     } 
    } 
} 

在这一点上它做的工作。我不确定这是最好的方式或足够快。

相关问题