mardi 15 janvier 2019

Dynamically casting an Entity Model from SQL query results

I need to dynamically cast a SQL return value to a model like this

var data = _db.Query<myModel>(myStoredProcedure, p, commandType: System.Data.CommandType.StoredProcedure);

The above works as it should as the model is explicit in the casting.

However, myModel could be any type of model class that I have in my project. I am able to get the actual model through reflection and the use of a string variable called "TableName" I thought I could go this routine to set it but I get the error of 'entityObject is a variable but used like a type'

 //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.Models")).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 ctx = new MyProject.Models.Entities();

                       //Create the DBSet here
                        System.Data.Entity.DbSet myDbSet = ctx.Set(type);

                        //Now create the actual entity reference which is just an object at this point
                        var entityObject = myDbSet.Create();


--> Errors here var data = _db.Query<entityObject>(myStoredProcedure, p, commandType: System.Data.CommandType.StoredProcedure);
}





Aucun commentaire:

Enregistrer un commentaire