I really can't figure it out ...
I am trying to achieve the following result using reflection:
_builder.Entity<Post>().HasKey(p => p.Id);
Let me introduce variables ... _builderhas a type DbModelBuilder, but Posthas a Idtype property Guid.
The code below contentTypewraps System.Type:
var config = _builder.GetType()
.GetMethod("Entity")
.MakeGenericMethod(contentType.Type)
.Invoke(_builder, null);
var hasKey = config.GetType().GetMethod("HasKey");
var expressionKey = typeof(Expression<>)
.MakeGenericType(typeof(Func<,>)
.MakeGenericType(contentType.Type, typeof(Guid)));
var paramEx = Expression.Parameter(contentType.Type, "t");
var lambdaEx = Expression.Lambda(Expression.Property(paramEx, "Id"), paramEx);
hasKey.MakeGenericMethod(typeof(Guid))
.Invoke(_builder, new[] { lambdaEx });
HasKey may I help:
public EntityTypeConfiguration<TEntityType> HasKey<TKey>(Expression<Func<TEntityType, TKey>> keyExpression);
... where TEntityTypeshould have type Postand TKeytype Guid...
A type exception is TargetExceptionthrown (the last time Invoke was called above):
The object does not match the type of target.
I tried all the ideas that I could come up with, and yet I cannot match the type of goal.
Any help is appreciated.