无法在 EF Core 中映射用户定义的数据库函数

问题描述 投票:0回答:1

我有一个简单的数据库函数,它接受两个整数参数并返回一个日期。我正在尝试映射 EF Core 中的函数,以便我可以从我的代码访问它。

我读过很多关于此的文章,并尝试过以下方法:

在 dbContext 中我尝试定义函数如下:

[DbFunction("GetLastPlayDate")]
public static bool GetLastPlayDate(int GroupId, int PlayerId)
{
    throw new Exception(); // this code doesn't get executed; the call is passed through to the database function
}

然后,在

OnModelCreating
方法中,我做了以下操作:

modelBuilder.HasDbFunction(typeof(dbContext)
            .GetMethod(nameof(GetLastPlayDate), new[] { typeof(int), typeof(int) }))
            .HasName("GetLastPlayDate");

我添加了迁移。然后我期望能够做这样的事情:

var date = db.GetLastPlayDate(1,2)

该函数未定义。请帮忙!

我尝试添加该功能,但我的

dbContext
无法使用该功能。

c# entity-framework-core
1个回答
0
投票

您必须在 Linq 查询中使用 C# 函数

GetLastPlayDate(1,2)
。例如,请参阅下面的代码:

var db = serviceProvider.BuildServiceProvider().GetService<DatabaseContext>();
   
var games = db.Games.Select(x => DatabaseContext.GetLastPlayDate(4, 6) == true).ToList();
   
© www.soinside.com 2019 - 2024. All rights reserved.