繁体   English   中英

实体框架选择投影委托不起作用(按要求)

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

如果执行此操作并使用SQL事件探查器分析SQL流量,则SELECT请求所有表列:

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

如果我这样做,则SELECT正确地仅包括属于投影一部分的列:

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

MakeExtentSearchProjection()为:

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

有什么区别,为什么第一个不起作用?

最大的区别是您使用Select方法的哪个重载:

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

要么

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

请注意,第一个操作于IQueryable对象,第二个操作于IEnumerable对象。 在EntityFramework中使用IEnumerable扩展会导致EF检索所有数据,并在程序端进行投影(EF不会创建适当的SQL查询)。

要解决您的问题,只需将您的方法定义更改为:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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