如何使用类型创建对象

本文关键字:创建对象 类型 何使用 | 更新日期: 2023-09-27 18:12:27

我想覆盖方法SaveChanges()从DbContext中添加一些控件。我的想法是找到所有被修改过的对象,并重新加载它们以前的值,以便与新的值进行比较。

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 type是DbRawSqlQuery。我找不到如何创建一个类型为"myType"的对象,然后查询数据库找到它。

如何使用类型创建对象

我发现这是解决方案:

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

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