使用 EF core 2.1 调用 DbFunction
Call DbFunction with EF core 2.1
我尝试调用存储在我的数据库中的标量函数。
这是我的代码:
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();
我尝试调用存储在我的数据库中的标量函数。 这是我的代码:
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();