我尝试调用存储在数据库中的标量函数。 这是我的代码:
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));
答案 0 :(得分:1)
好吧,我明白了。
问题是您不能直接调用标量函数(我不知道为什么),它必须封装在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();