反射:以泛型参数和 lambda 表达式作为参数的方法
我真的无法弄清楚这个问题...
我正在尝试使用反射实现以下结果:
_builder.Entity<Post>().HasKey(p => p.Id);
让我介绍变量... _builder
的类型为 DbModelBuilder
和 Post
具有 Guid
类型的属性 Id
。
在下面的代码中, contentType
包装了 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
定义可能会有所帮助:
public EntityTypeConfiguration<TEntityType> HasKey<TKey>(Expression<Func<TEntityType, TKey>> keyExpression);
... 其中 TEntityType
应该是 Post
类型,TKey
类型是 Guid
...
抛出 TargetException
类型的异常(在最后一次调用上面的 Invoke):
对象与目标类型不匹配。
我已经尝试了所有我能想到的想法,但仍然无法匹配目标类型。
任何帮助表示赞赏。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在上次调用 Invoke 时,您指定了错误的实例参数。应该是“config”而不是“_builder”
In your last call to Invoke, you specified the wrong instance parameter. Should be 'config' rather than '_builder'
愚蠢的我,我没有任何借口...
如何使用实体框架和实体框架反思:
Silly me, I have no excuses...
How-to Entity Framework & Reflection: