Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflection: method with generic argument and lambda expression as parameter

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.

like image 731
maxbeaudoin Avatar asked Nov 04 '22 12:11

maxbeaudoin


1 Answers

In your last call to Invoke, you specified the wrong instance parameter. Should be 'config' rather than '_builder'

like image 54
Polity Avatar answered Nov 09 '22 16:11

Polity