mardi 15 janvier 2019

Converting an Expando Object to a Class dynamically?

I am getting a list of table records via a stored procedure using dapper.

 var data = _db.Query<System.Dynamic.ExpandoObject>('myStoredPoroc', p, commandType: System.Data.CommandType.StoredProcedure);

Before that I am getting the actual model class as an entity using reflection

 //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();
                     }

Once the data returns I try to use the below methods to convert the list of records to its actual entity.

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

The issue here is record is null. Why am I unable to cast the expandoObject to the entity model? It should be a 1 to 1 map.





Aucun commentaire:

Enregistrer un commentaire