如何使用Type创建对象

时间:2014-07-11 17:13:45

标签: c# dbcontext

我想从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 个答案:

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

此时它正在完成这项工作。我不确定这是最好的方式还是足够快。