How can I combine multiple refactored Select expressions in Linq (in EF or SQL)?

Let's say I have this view model:

public class SeriesLinkViewModel
{
    public static Expression<Func<Series, SeriesLinkViewModel>> FromSeries =
        s => new SeriesLinkViewModel
        {
            Name = s.Name,
            Slug = s.Slug,
        };

    public string Name { get; set; }
    public string Slug { get; set; }
}

I attached the projection function there for convenience, so now I can say something like:

var links = dc.Series.Select(SeriesLinkViewModel.FromSeries);

Tall. But what should I do if I want to add to this request? Say I also wanted to pull a column Descriptionfrom a table. Usually I could just do select new { }and put it there Description, but I can't do it because I can only put one projection function in `.Select ().

I was hoping I could do something like this:

q = from s in dc.Series
    select new
    {
        Series = SeriesLinkViewModel.FromSeries.Compile()(s),
        Description = s.Description
    };

But I get an exception:

System.InvalidCastException: cannot cast object of type 'System.Linq.Expressions.FieldExpression' to print 'System.Linq.Expressions.LambdaExpression'.

? , TransactionScope , , .

+3
4

LinqKit:

var fs = SeriesLinkViewModel.FromSeries; //needs to be local for some reason
q = from s in dc.Series.AsExpandable() //enables LinqKit to do its magic
    select new
    {
        Series = fs.Invoke(s), //and voila!
        Description = s.Description
    };
+6
+2

, , , - ,

private IQueryable<SeriesLinkViewModel> FromSeries(IQueryable<Series> seriesQuery)
{
    return from s in seriesQuery
           select new SeriesLinkViewModel
           {
                Name = s.Name,
                Slug = s.Slug
           };
}

, , .

return FromSeries(from s in Series
                  where s.Name == "foo"
                  select s);

, , , , .

0

, , .

public class SeriesLinkViewModel
{
    public static Expression<Func<Series, SeriesLinkViewModel>> FromSeries =
        s => new SeriesLinkViewModel
        {
            Name = s.Name,
            Slug = s.Slug,
        };

    public string Name { get; set; }
    public string Slug { get; set; }
}

public class SeriesLinkExtendedViewModel: SeriesLinkViewModel
{
    public new static Expression<Func<Series, SeriesLinkExtendedViewModel>> FromSeries = 
        SeriesLinkViewModel.FromSeries.Merge(s => new SeriesLinkExtendedViewModel
        {
            Description = s.Description
        });

    public string Description { get; set; }
}

// Somewhere else...
var q = from s in dc.Series.Select(SeriesLinkExtendedViewModel.FromSeries);

"" , , , : Name, Slug Description.

: https://coding.abel.nu/2013/01/merging-expression-trees-to-reuse-in-linq-queries/

0

Source: https://habr.com/ru/post/1774932/


All Articles