EF Core Entity on Type

c# entity-framework-core


I am trying to map entities dynamically in EF Core. So instead of having multiple relationship specified explicitly in the dbcontext I am trying to do it with reflection. So I have this thus far:

var props = modelBuilder.Model.GetEntityTypes()
            .SelectMany(t => t.GetProperties())
            .Where(p => p.IsForeignKey());

foreach (var prop in props)
    var name = prop.Name.Split(new[] { "Id" }, StringSplitOptions.None)[0];

    var parentTableType = prop.DeclaringEntityType.ClrType
        .GetFields(BindingFlags.Instance | BindingFlags.NonPublic)
        .Where(f => f.FieldType != typeof(long))
        .First(f => f.Name.Contains(name))

    var childTableType = prop.DeclaringEntityType.ClrType
        .GetFields(BindingFlags.Instance | BindingFlags.NonPublic)
        .Where(f => f.FieldType == typeof(long))
        .First(f => f.Name.Contains("Id"))

So this is working as I expect it to, I am getting the Type of each one of the tables. Now the problem is coming in when I try to actually create the relationship. The Type's of the two tables are obviously variables so I cannot use them as explicit Type's as follows:


Is there anyway to convert the variables to concrete Types at runtime to allow the above to happen or am I wasting my time trying to do this?

2/13/2019 7:42:54 AM

Accepted Answer

There are many Fluent API non generic method overloads accepting string type name or Type type arguments.

Since you have Type variables, you could use the corresponding Entity and HasMany overloads:

2/13/2019 11:16:30 AM

Popular Answer

I have solved the problem and it is all working as it should. I have uploaded the specific code to GitHub as a GIST if anyone is interested.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow