动态制作lambda表达式 [英] Making lambda expression dynamically

查看:172
本文介绍了动态制作lambda表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  modelBuilder.Entity(Of Model).HasKey(Function(item As模型)New with {item.PropertyA,item.PropertyB})

映射复合主键



我需要编写一个泛型函数,如:

  modelBuilder.Entity (TModelo).HasKey(MakeLambda({PropertyA,PropertyB})

私有函数MakeLambda(TModelo)(nameProperties As String())As Expression(Of Func(Of TModelo,对象))
Dim type = GetType(TModelo)

Dim listProperties作为新列表(表达式)
Dim参数= Expression.Parameter(type,item)
对于每个n As String在nameProperties中
Dim refProperty = type.GetProperty(n)
listProperties.Add(Expression.MakeMemberAccess(parameter,refProperty))
下一个

Dim arrayInit = Expression.NewArrayInit(GetType(Obje ct),listProperties)

此时系统无法创建新表达式

  Dim newExpression = Expression.Lambda(Of Func(Of TModelo,Object))(arrayInit)

返回newExpression
结束函数

可能有人有另一个解决这个问题的解决方案p>

解决方案

这样做。
dynamic newExpression = Expression.Lambda>(arrayInit,parameter);



但是这还没有为我工作。
我需要这样的东西...

  HasKey(p => new {p.FAMILY, CACHE_FAMILY,p.CUSTOMER_CODE,p.CCC,p.OPERATION,p.EVAL_CODE,p.VDT_FLAG,p.TEST_PLATFORM,p.PCBA_VENDOR}); 


In Entity Framework I usually do something like:

modelBuilder.Entity(Of Model).HasKey(Function(item As Model) New With {item.PropertyA, item.PropertyB })

to map a composite primary key

I need to write a generic function like:

modelBuilder.Entity(Of TModelo).HasKey( MakeLambda({"PropertyA", "PropertyB" })

Private Function MakeLambda(Of TModelo)(nameProperties As String()) As Expression(Of Func(Of TModelo, Object))
        Dim type = GetType(TModelo)

        Dim listProperties As New List(Of Expression)
        Dim parameter = Expression.Parameter(type, "item")
        For Each n As String In nameProperties
            Dim refProperty = type.GetProperty(n)
            listProperties.Add(Expression.MakeMemberAccess(parameter, refProperty))
        Next

        Dim arrayInit = Expression.NewArrayInit(GetType(Object), listProperties)

In this point the system fails creating the new expression

        Dim newExpression = Expression.Lambda(Of Func(Of TModelo, Object))(arrayInit)

        Return newExpression
End Function

May be somebody has another solution to this problem

解决方案

This will do. dynamic newExpression = Expression.Lambda>(arrayInit, parameter);

But this still not work for me yet. I need something like this...

HasKey(p => new { p.FAMILY, p.CACHE_FAMILY, p.CUSTOMER_CODE, p.CCC, p.OPERATION, p.EVAL_CODE, p.VDT_FLAG, p.TEST_PLATFORM, p.PCBA_VENDOR });

这篇关于动态制作lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆