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
Entity framework 使用实体属性作为参数的EF自定义选择_Entity Framework_Linq - Fatal编程技术网

Entity framework 使用实体属性作为参数的EF自定义选择

Entity framework 使用实体属性作为参数的EF自定义选择,entity-framework,linq,Entity Framework,Linq,对于每个表(我有很多表),我在ASP.Net核心应用程序中提供了查找RESTAPI方法 这是我对每个表的查询的一部分: context.Users.Select(t => new ViewLookupModel() { id = t.Id, title = t.DisplayName }) //...... context.Groups.Select(t => new ViewLookupModel()

对于每个表(我有很多表),我在ASP.Net核心应用程序中提供了查找RESTAPI方法

这是我对每个表的查询的一部分:

    context.Users.Select(t => new ViewLookupModel()
    {
        id = t.Id,
        title = t.DisplayName
    })
    //......
    context.Groups.Select(t => new ViewLookupModel()
    {
        id = t.Id,
        title = t.Name
    })
但我想为每个表编写收缩代码的扩展。大概是这样的:

        public static IQueryable<ViewLookupModel> SelectLookup<T>(this IQueryable<T> query, Func<int> idField, Func<string> titleField)
        {
            return query.Select(t => new ViewLookupModel()
            {
                id = idField(),
                title = titleField()
            });
        }
但我得到了一个错误:

委托“Func”不接受1个参数

这个问题似乎很相似,但我无法让它发挥作用


我还对使用自定义选择扩展方法查询数据库时出现的任何性能问题感兴趣。

将扩展方法更改为此,然后重试。扩展方法以T作为输入,并返回相应的int或string等

public static IQueryable<ViewLookupModel> SelectLookup<T>(this IQueryable<T> query, Func<T,int> idField, Func<T,string> titleField)
    {
        return query.Select(t => new ViewLookupModel()
        {
            id = idField(t),
            title = titleField(t)
        });
    }
public static IQueryable SelectLookup(此IQueryable查询、Func idField、Func titleField)
{
返回query.Select(t=>newviewlookupmodel()
{
id=idField(t),
标题=标题字段(t)
});
}

这无法转换为SQL,因此在EF6和早期版本中不起作用(运行时异常),而在EF Core中会导致客户端计算,因此效率低下。
public static IQueryable<ViewLookupModel> SelectLookup<T>(this IQueryable<T> query, Func<T,int> idField, Func<T,string> titleField)
    {
        return query.Select(t => new ViewLookupModel()
        {
            id = idField(t),
            title = titleField(t)
        });
    }