简体   繁体   中英

Entity framework select projection delegate doesn't work (as required)

If I do this and profile SQL traffic with SQL profiler the SELECT requests ALL of the table columns:

_db.Routes.Select(MakeExtentSearchProjection()).ToList();

If I do this the SELECT correctly includes only the columns that are part of the projection:

_db.Routes.Select(r => new RouteExtentSearchProjection {
                        GeoPathSmall = r.GeoPathSmall,
                        ID = r.ID,
                        IsPublished = r.IsPublished,
                        Sort = r.Sort,
                        Title = r.Title })
                        .ToList());

With MakeExtentSearchProjection() being:

private Func<Route, RouteExtentSearchProjection> MakeExtentSearchProjection()
        {
            return r => new RouteExtentSearchProjection()
            {
                ID = r.ID,
                Title = r.Title,
                GeoPathSmall = r.GeoPathSmall,
                IsPublished = r.IsPublished
            };
        }

What's the difference and why doesn't the first one work?

The big difference is which overload of the Select method you use:

public static IQueryable<TResult> Select<TSource, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TResult>> selector)

or

public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector)

Notice that the first one operates on an IQueryable object and the second one operates on an IEnumerable object. Using IEnumerable extensions with EntityFramework causes that EF retrieves ALL data and a projection is done on your program side (EF doesn't create an appropriate SQL query).

To solve your problem just change your method definition to:

private Expression<Func<Route, RouteExtentSearchProjection>> MakeExtentSearchProjection()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM