Reputation: 2411
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))
.FieldType;
var childTableType = prop.DeclaringEntityType.ClrType
.GetFields(BindingFlags.Instance | BindingFlags.NonPublic)
.Where(f => f.FieldType == typeof(long))
.First(f => f.Name.Contains("Id"))
.DeclaringType;
}
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:
modelBuilder.Entity<parentTableType>()
.HasMany<childTableType>();
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?
Upvotes: 3
Views: 260
Reputation: 205539
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:
modelBuilder.Entity(parentTableType)
.HasMany(childTableType);
Upvotes: 2