开发者

Making lambda expression dynamically

开发者 https://www.devze.com 2023-03-19 23:35 出处:网络
In Entity Framework I usually do something like: modelBuilder.Entity(Of Model).HasKey(Function(item As Model) New With {item.PropertyA, item.PropertyB })

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 Ex开发者_JAVA百科pression(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 });
0

精彩评论

暂无评论...
验证码 换一张
取 消