Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 实体框架选择投影代理不';t工作(根据需要)_C#_Entity Framework_Delegates - Fatal编程技术网

C# 实体框架选择投影代理不';t工作(根据需要)

C# 实体框架选择投影代理不';t工作(根据需要),c#,entity-framework,delegates,C#,Entity Framework,Delegates,如果我这样做并使用SQL profiler分析SQL流量,SELECT将请求所有表列: _db.Routes.Select(MakeExtentSearchProjection()).ToList(); 如果正确执行此操作,则选择仅包括作为投影一部分的列: _db.Routes.Select(r => new RouteExtentSearchProjection { GeoPathSmall = r.GeoPathSmall,

如果我这样做并使用SQL profiler分析SQL流量,SELECT将请求所有表列:

_db.Routes.Select(MakeExtentSearchProjection()).ToList();
如果正确执行此操作,则选择仅包括作为投影一部分的列:

_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
            };
        }
private Func MakeExtentSearchProjection()
{
返回r=>newrouteextentsearchprojection()
{
ID=r.ID,
标题=r.标题,
GeoPathSmall=r.GeoPathSmall,
IsPublished=r.IsPublished
};
}

区别是什么?为什么第一种方法不起作用?

最大的区别是您使用的选择方法的重载:

public static IQueryable<TResult> Select<TSource, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TResult>> selector)
公共静态IQueryable选择(此IQueryable源、表达式选择器)

公共静态IEnumerable选择(此IEnumerable源,Func选择器)
请注意,第一个对IQueryable对象进行操作,第二个对IEnumerable对象进行操作。将IEnumerable扩展与EntityFramework一起使用会导致EF检索所有数据,并在程序端执行投影(EF不会创建适当的SQL查询)

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

private Expression<Func<Route, RouteExtentSearchProjection>> MakeExtentSearchProjection()
私有表达式MakeExtentSearchProjection()

有道理。我明天会试试这个。
private Expression<Func<Route, RouteExtentSearchProjection>> MakeExtentSearchProjection()