gpt4 book ai didi

ef-core-2.1 - 使用 EF core 2.1 调用 DbFunction

转载 作者:行者123 更新时间:2023-12-04 01:50:40 26 4
gpt4 key购买 nike

我尝试调用存储在我的数据库中的标量函数。这是我的代码:

public class PronosticDbContext : DbContext
{
public PronosticDbContext(DbContextOptions<PronosticDbContext> options) : base(options)
{

}

[DbFunction(FunctionName = "GetPlayerPointsForDay", Schema = "dbo")]
public static int GetPlayerPointsForDay(int dayId, int userId) => throw new NotSupportedException();
}

电话:

private IQueryable<PlayerRankingData> GetPlayerRanking(int? dayId)
{
return Context.Days.Where(x => x.Id == dayId.Value).Select(x => new PlayerRankingData
{
// Some properties
Users = x.Season.Users.Select(us => new PlayerRankingData.User
{
// Other properties
Last = PronosticDbContext.GetPlayerPointsForDay(x.Id, us.User.Id),
// Others again
}).OrderByDescending(u => u.Points).ThenByDescending(u => u.Last).ThenBy(u => u.Login)
});
}

我不明白为什么,但我总是转到 NotSupportedException,我的标量函数从未被调用。为什么我错过了?

我也这样试过,结果一样。

modelBuilder
.HasDbFunction(typeof(PronosticDbContext).GetMethod(nameof(GetPlayerPointsForDay)))
.HasSchema("dbo")
.HasName(nameof(GetPlayerPointsForDay));

最佳答案

好的,我知道了。

问题是你不能直接调用标量函数(我不知道为什么),它必须封装在一个 linq 查询中,像这样:

Last = Context.Users.Select(u => PronosticDbContext.GetPlayerPointsForDay(x.Id, us.User.Id)).FirstOrDefault()

仅此而已。无需在 DbContext 中声明,这就足够了:

[DbFunction]
public static int? GetPlayerPointsForDay(int dayId, int userId) => throw new NotSupportedException();

关于ef-core-2.1 - 使用 EF core 2.1 调用 DbFunction,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53269315/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com