Moving C# function to expression for use in Entity Framework / SQL Select

c# entity-framework expression expression-trees sql-server

Question

I would want to convert a few tiny C# functions and calculated columns from views to Expressions so they can run directly on the datasource in native T/SQL.

I can perform this directly in the Select, but for testing and reuse, I'd want to transfer it to a common function.

var results = context
    .Products
    .Select(p => new StockDto
    {
        Stock = p.GoodStock - p.LiveStock // Real version is more complex.
    });

When I attempted to write a function that returned an expression, C# tried to assign the expression rather than the expression's result, and the function wouldn't compile. It also fails to build when the following Expression variable is used.

public static readonly Expression<Func<DataModel.Product, int>> StockLevel = 
    expr => expr.GoodStock - 10;

I'm used to adding where clauses with expressions, but I'm not sure how to make an expression that returns a string from a select statement.

I want to carry out this;

var results = context
    .Products
    .Select(p => new StockDto
    {
        Stock = StockExpression // StockExpression is written in C#
    });

I don't see how to generate an Expression Tree using LinqKit; it appears to be about making predicates (Where clauses) simpler to deal with. Is the only way to do this to manually construct a complicated expression tree (which I'd want to avoid since it obscures the code's meaning)?

1
3
6/2/2016 5:28:17 PM

Accepted Answer

You ought should be able to use zzz-3 zzz. You ought to dialInvoke to incorporate one phrase into another.

The combined expressions may be "expanded" in one of two ways:

You may either callAsExpandable on theIQueryable such that it automatically "expands" phrases like this:

var results = context
    .Products
    .AsExpandable()
    .Select(p => new StockDto
    {
        Stock = StockLevel.Invoke(p) 
    });

Alternatively, you may manually extend the phrase before using it, like in:

Expression<Func<Product, StockDto>> expression = p => new StockDto
{
    Stock = StockLevel.Invoke(p) 
};

expression = expression.Expand();

var results = context
    .Products
    .Select(expression);
1
10/31/2017 6:47:10 PM

Popular Answer

Examine Microsoft.Linq.Translations. You may use expression trees to specify properties and then utilize those properties in queries. If you want to really grasp how select reuse works, look out this answer or LinqKit, which is your buddy for select reuse:)



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow