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

走远了吗. 提交于 2019-12-06 03:42:01
Yacoub Massad

LinqKit should work for you. You should call Invoke to use one expression in another.

You have two options for "expanding" the merged expressions:

You either invoke AsExpandable on the IQueryable so that it "expands" expressions automatically like this:

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

Or you expand the expression manually before using it like this:

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

expression = expression.Expand();

var results = context
    .Products
    .Select(expression);
Edgars Pivovarenoks

I hope I understood your question, take a look at this discussion. You don't need extra argument, but the idea how to arrange things together might apply to your case.

How to reuse LINQ Select Expression with arguments

private static Expression<Func<Singles, SearchSingles>> CreateSearchSelector()
{
    return s =>
        new SearchSingles
        {
            Foo = foo,
        };
}

// Then use it like this
DataContext.Single.Select(CreateSearchSelector()).ToList();
MBoros

Look at Microsoft.Linq.Translations. It allows you to define properties with expression trees, and then use them in queries. For select reuse, indeed LinqKit is your friend, or check out this answer, if you really want to understand how it works :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!