0

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!

2
  • 1
    Casting or using generics like your DbSet<new_type> is a compile time operation. Creating types at runtime is, well, a runtime operation. There is no way to tell the compiler about these types that do not exist at compile time. There are at least two directions you can take, use oop and compile time known base-classes/interfaces. Or use reflection all the way down for every call or member access. Commented Apr 16, 2020 at 13:46
  • Why is it not possible to define your DbSet for your database at compile time? If you want to dynamically query a database then maybe EF core isn't the best solution? Commented Apr 16, 2020 at 13:58

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.