我正在使用dapper通过存储过程获取表记录列表。
var data = _db.Query<System.Dynamic.ExpandoObject>('myStoredPoroc', p, commandType: System.Data.CommandType.StoredProcedure);
在我使用反射将实际的模型类作为一个实体之前
//First we need to find the project that holds all of our entity models in the assembly
var assembly = AppDomain.CurrentDomain.GetAssemblies().Where(x => x.FullName.Contains("MyProject.Model")).FirstOrDefault();
//Now we need to search through the assembly to match the Entity to the supplied TableName
var type = assembly.GetTypes()
.FirstOrDefault(t => t.Name == localTableName);
//Once found then we create a dynamic instance of the entity using reflection
if (type != null)
{
var context = new Model.Entities();
//Create the DBSet here
System.Data.Entity.DbSet myDbSet = contextSet(type);
//Now create the actual entity reference which is just an object at this point
var entityObject = myDbSet.Create();
}
一旦数据返回,我将尝试使用以下方法将记录列表转换为其实际实体。
if (data.Any())
{
var record = DynamicCast(data, entityObject.GetType());
}
dynamic DynamicCast(object entity, Type to)
{
var openCast = this.GetType().GetMethod("Cast", BindingFlags.Static | BindingFlags.NonPublic);
var closeCast = openCast.MakeGenericMethod(to);
return closeCast.Invoke(entity, new[] { entity });
}
static T Cast<T>(object entity) where T : class
{
return entity as T;
}
这里的问题是记录为空。为什么我无法将expandoObject强制转换为实体模型?它应该是一对一的地图。