C# 500从.net core 2.1调用标量数据库函数时出错

C# 500从.net core 2.1调用标量数据库函数时出错,c#,.net,asp.net-core,entity-framework-core,C#,.net,Asp.net Core,Entity Framework Core,我试图从.NET Core 2.1 Web API调用数据库中的标量函数,以获取员工的主管;我的数据库中的函数需要输入员工id,并返回主管的id。它工作正常,名为dbo.fn\u GetDirectorID 我想在我的Web API中创建一个端点来调用此函数,获取directorID,然后将该director的employee对象发送回我的客户端。所以我在寻找在线资源,我发现我想哇,这是可能的,让我们试试看,所以我遵循了他们的教程,我现在在我的上下文中有了一个GetDirectorID数据库函数

我试图从.NET Core 2.1 Web API调用数据库中的标量函数,以获取员工的主管;我的数据库中的函数需要输入员工id,并返回主管的id。它工作正常,名为
dbo.fn\u GetDirectorID

我想在我的Web API中创建一个端点来调用此函数,获取
directorID
,然后将该director的employee对象发送回我的客户端。所以我在寻找在线资源,我发现我想哇,这是可能的,让我们试试看,所以我遵循了他们的教程,我现在在我的上下文中有了一个
GetDirectorID
数据库函数,如所述链接

[DbFunction("fn_GetDirectorID", "dbo")]
public static int GetDirectorID(int id)
{
    throw new NotImplementedException();
}
然后在我的控制器里,我要做这样的事情

[HttpGet("GetDirector/{id}")]
public async Task<IActionResult> GetDirector([FromRoute] int id)
{
    var directorID = KPContext.GetDirectorID(id);

    var director = await _context.Employees.FindAsync(directorID);

    if (director == null)
    {
        return NotFound();
    }

    return Ok(director);
}
有人能帮忙吗?我将不胜感激

我也试过这个

 [HttpGet("GetDirector/{id}")]
        public async Task<IActionResult> GetDirector([FromRoute] int id)
        {


            var director = await _context.Employees.FindAsync(KPContext.GetDirectorID(id));

            if (director == null )
            {
                return NotFound();
            }

            return Ok(director);
        }
[HttpGet(“GetDirector/{id}”)]
公共异步任务GetDirector([FromRoute]int id)
{
var director=await_context.Employees.FindAsync(KPContext.GetDirectorID(id));
if(director==null)
{
返回NotFound();
}
返回Ok(主管);
}

我会尝试linq查询,因为我认为还不支持纯EF

   [HttpGet("GetDirector/{id}")]
    public async Task<IActionResult> GetDirector([FromRoute] int id)
    {
        var director =  from p in _context.Employees where p.EmployeeId == KPContext.GetDirectorID(id) select p;

        if (director == null )
        {
            return NotFound();
        }

        return Ok(director);
    }
[HttpGet(“GetDirector/{id}”)]
公共异步任务GetDirector([FromRoute]int id)
{
var director=from p in _context.EmployeeId==KPContext.GetDirectorID(id)选择p;
if(director==null)
{
返回NotFound();
}
返回Ok(主管);
}

这会让你得到你需要的,让我知道它是否适合你!!干杯,祝您愉快。

这样的标量函数只能在LINQ to Entities查询中使用(不能在客户端执行,必须是SQL查询的一部分)

这意味着您不能使用
FindAsync
,因此请改用
FirstOrDefaultAsync
SingleOrDefaultAsync

var director = await _context.Employees
    .SingleOrDefaultAsync(e => e.Id == KPContext.GetDirectorID(id));
这也比
FindAsync
有优势,如果您有相关数据,您可以立即加载(
包含
/
然后包含
)相关数据

另外,请注意(链接中未提及)如果标量函数是在目标
DbContext
派生类以外的类中定义的,则它不会自动注册,因此您需要向
DbContext
派生类
OnModelCreating
覆盖中添加类似的内容(当然,如果不是
KPContext
类):


有关更多信息,请参阅文档。

支持此功能,请参阅@Ivan Stoev answer,但此功能确实有效,满足了我的需求。谢谢您的支持
var director = await _context.Employees
    .SingleOrDefaultAsync(e => e.Id == KPContext.GetDirectorID(id));
modelBuilder.HasDbFunction(() => KPContext.GetDirectorID(default(int)));