我在SQL Server上有一个表值函数
CREATE FUNCTION [dbo].[FStatusDepo]
(
@ProvozID int, @ZonaID int NULL, @minutesWarning int
)
RETURNS TABLE
AS
RETURN
(
SELECT
q.[DepoID]
,SUM(CASE WHEN v.Vjezd IS NOT NULL AND datediff(mi, v.Vjezd, GETDATE())>@minutesWarning THEN 1 ELSE 0 END) AS VjezduPoLhute
,SUM(CASE WHEN v.Vjezd IS NOT NULL AND datediff(mi, v.Vjezd, GETDATE())<=@minutesWarning THEN 1 ELSE 0 END) AS VjezduVLhute
FROM
...
我有一个使用ASP.NET Core 2.1和EF Core 2.1的新项目。
I have read,我可以在DbContext中定义新的Query
类型:
public class StatusDepo
{
public int DepoID { get; set; }
public int VjezduPoLhute { get; set; }
public int VjezduVLhute { get; set; }
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder
.Query<StatusDepo>().ToView("FStatusDepo");
当我看示例时:
https://github.com/aspnet/EntityFrameworkCore/blob/dev/samples/QueryTypes/Program.cs
我在那里看到,我可能也应该将此行添加到DbContext中:
public DbQuery<StatusDepo> StatusDepos { get; set; }
然后我可以执行:
using (DixieContext db = new DixieContext())
{
var listStatusDepo =
db.StatusDepos.FromSql("SELECT * FROM [dbo].[FStatusDepo] (1, 1, 20)").ToList();
}
这行得通,但行:
modelBuilder.Query<StatusDepo>().ToView("FStatusDepo")
完全没有目的,是否有用于参数化视图的其他构造,还是我应该删除该行并仅使用FromSql?
答案 0 :(得分:1)
是否有用于参数化视图的其他构造,还是应该删除该行并仅使用FromSql?
是的。您应该删除modelBuilder.Query<StatusDepo>().ToView("FStatusDepo")
在这里什么也不做,因为您没有将类StatusDepo
映射到SQL VIew,但是您正在使用返回表的SQL Function。
EF Core ToView()
方法用于将类映射到SQL View(并在需要时将映射属性配置到列),因此您无需编写SQL,因为EF知道如何为您生成它。
对于您而言,您的以下代码就足够了:
using (DixieContext db = new DixieContext())
{
var listStatusDepo = db.StatusDepos.FromSql("SELECT * FROM [dbo].[FStatusDepo] (1, 1, 20)").ToList();
}