2014-07-11 169 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 
      } 
     } 
    } 
} 

在這一點上它做的工作。我不確定這是最好的方式或足夠快。

相關問題