Is there a way to use `dynamic` in lambda expression tree?

后端 未结 3 914
感动是毒
感动是毒 2021-01-17 10:16

First, spec. We use MVC5, .NET 4.5.1, and Entity framework 6.1.

In our MVC5 business application we have a lot of repetitive CRUD code. My job is to \"automate\" mos

3条回答
  •  粉色の甜心
    2021-01-17 10:27

    No, you cannot use dynamic in a Linq to Entities query. But you can build the Lambda Expression at runtime.

    public virtual Expression> UpdateCriterion()
    {
        var param = Expression.Parameter(typeof(TSubclass));
        var body = Expression.Convert(Expression.Property(param, "ID"), typeof(object));
    
        return Expression.Lambda>(body, param);
    }
    

    If the TSubclass type does not have an ID property Expression.Property(param, "ID") will throw an exception.

    Additionally you could use the MetadataWorkspace from your entity model to get the Primary Key column for TSubclass.

提交回复
热议问题