Making lambda expression dynamically

2019-09-01 17:13发布

问题:

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

回答1:

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 });