jeudi 16 avril 2020

Using types created at runtime in C# .Net Core

Technological requirements:

MS SQL DB, .NET Core 3.1, EF Core, C#

That what should be done:

I need to create some metadata-driven solution in C# that has to be able to connect to a DB and then to retrieve the data from any table defined in a JSON file, which program gets as an input. In the JSON file schema, table and columns are listed. For example:

{
   schema: 'dbo',
   table: 'customers',
   columns: [
              {
                name: 'FirstName',
                type: 'string'
              },
              {
                name: 'Age',
                type: 'integer'
              }
            ]
}

Solution should be able to create class (Type) reflecting the needs of those of the current JSON file. After that, it should use this new type to set up a DbSet<new_type> CustomTypeList { get; set; } in DBContext and subsequently configure it with IEntityTypeConfiguration.

What I have done so far:

I used the code from this post and thus implemented some type of RuntimeCustomTypeCreation class that returns a new type created right after the beginning of my program by using System.Reflection and System.Reflection.Emit namespaces. The new type reflects exactly the structure the JSON ordered us. A new instance of that type now can be created easily with System.Activator.CreateInstance(...) function.

Problem I can't get solved:

How can I use my newly created runtime-type in my application as for example any class written as code before compilation and execution? I need to be able to do something like already written above and that is:

DbSet<new_type> CustomTypeList { get; set; }

Do I have to "register" my newly created type somewhere? Is this even possible? Thank you!





Aucun commentaire:

Enregistrer un commentaire