I really can't figure this one out...
I'm trying to achieve the following result using reflection:
_builder.Entity<Post>().HasKey(p => p.Id);
Let me introduce the variables... _builder
is of type DbModelBuilder
and Post
has a property Id
of type Guid
.
In the code below, contentType
wraps a 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
definition might help:
public EntityTypeConfiguration<TEntityType> HasKey<TKey>(Expression<Func<TEntityType, TKey>> keyExpression);
... where TEntityType
should be of type Post
and TKey
of type Guid
...
Exception of type TargetException
is thrown (on the last call to Invoke above) :
Object does not match target type.
I have tried every idea I could come up with and still I can't match the target type.
Any help is appreciated.
In your last call to Invoke, you specified the wrong instance parameter. Should be 'config' rather than '_builder'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With