0

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
  • I can't parse the non-code parts of this question, if you are able have another try at the English grammar (having read the code improving the grammar won't help me answer the question but it might help someone else). Commented Jul 14, 2011 at 1:45

1 Answer 1

0

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 });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.