mardi 4 août 2015

Entity request with a class type created with string C# .net

In the context of data synchronization project between two distincts bases, we want a generic system where we don't need to know table name in advance in the code.

Class names are passed by string variable that we can transform to type thanks to reflection system.

string ma_classe = "string_classe";
Type ma_classe_type = Type.GetType(ma_classe);
object mon_instance = Activator.CreateInstance(ma_classe_type);

Until there no problem, an object of string_classe is created, but if data in the string are wrong, we are an error. So string_classe is the name of my class with her namespace.

Console.WriteLine(ma_classe_type.IsClass);

The previous line displays true and the object created type is the one present in the string ma_classe.

The problem comes later when we want to instantiate a simple List of ma_classe_type, but impossible to compile because the type isn't recognized.

The problem arise when we want to send the type to an entity function which returns a list, but it can't take it and raises an error for the type.

Below the entity function :

public List<T> GetAll<T>() where T : class
{
     return bdd.Set<T>().ToList();
}

Any idea? solutions or opinions are welcome.





Aucun commentaire:

Enregistrer un commentaire