mercredi 30 septembre 2020

Change discriminator value in Entity Framework

When using TPH(table per hierarchy) in EF core, the default behavior is to add a discriminator column that holds the derived type name. All subclasses are empty - they are only used to differentiate the rows in the database.

The scenario I'm facing is that I need to create and add some new types under runtime. Is this possible? I have tried to create a class dynamically, but I can't cast it to the subtype. When I'm inserting the value the discriminator value is the same as the base type. Another solution is that I could use raw SQL to insert the rows, but I don't know if it's possible to fetch the inserted rows from the database again. I tried the following:

            AssemblyName aName = new AssemblyName("DynamicAssemblyExample");
            AssemblyBuilder ab = AssemblyBuilder.DefineDynamicAssembly(aName,
                    AssemblyBuilderAccess.RunAndCollect);
       
            ModuleBuilder modb = ab.DefineDynamicModule("test");

            TypeBuilder tb = modb.DefineType("testType", TypeAttributes.Public | TypeAttributes.Class);
            tb.SetParent(typeof(MyBaseType));
            var typeInfo= tb.CreateTypeInfo();

            var objToInsertInDb = (MyBaseType) Activator.CreateInstance(typeInfo);

            baseTypeRepository.Add(objToInsertInDb);




Aucun commentaire:

Enregistrer un commentaire