从C#调用标量函数

3

我有一个在SQL数据库中的标量函数,我想使用Linq to Entity context调用它。

虽然我知道,你可以使用以下语法调用表函数。

    [DbFunction("Context", "TableFunc")]
    public virtual IQueryable<ModelEntity> TableFunc(int 
     Id)
    {
        var IdParam = new ObjectParameter("Id", typeof(int))
        {
            Value = Id
        };
        return (this as IObjectContextAdapter).ObjectContext
            .CreateQuery<ModelEntity>(
                "Context.TableFunc(@Id)",IdParam);
    }

然而,如果我在这个地方使用标量函数。

我会得到一个错误提示:“未指定名称参数”。

我的标量函数没有任何参数。

更新:

标量函数调用。

   [DbFunction("Context","GetValue")]
   public virtual IQueryable<short> GetValue()
    {
        return (this as  
     IObjectContextAdapter).ObjectContext.CreateQuery<short>
     ("Context.GetValue()");
    } 

.CreateQuery<ModelEntity>("SELECT ScalarFunc()"); 做了什么?(在返回值前面添加 SELECT 函数名称) - Caius Jard
参数'name'不能为空,也不能只包含空格。 - Mandar Jogalekar
你可以发布标量函数的代码吗? - Caius Jard
添加了标量函数。也尝试在Context.GetValue()之前加上SELECT。 - Mandar Jogalekar
尝试使用 new ObjectParameter("@Id", typeof(int)) - ASpirin
1个回答

0
我最近在 GitHub SourceCode 和这个link上找到了解决方案。 幸运的是,这种方法非常容易,只是没有以易于阅读的方式编码,因此我发现很难正确使用它。
public partial class MainDbContext : DbContext
    {
//....
  [DbFunction("CodeFirstDatabaseSchema", "IsAssignedIncludedInPickedRoles")]
    public static bool IsAssignedIncludedInPickedRoles(string pickedRoles, string assignedRoles)
    {
        throw new NotSupportedException();
    }

//.....
}

在“CodeFirstDatabaseSchema”字符串上使用义务中出现了歧义,我原以为它是文档的一部分,指导您使用dbContext名称或包含dbContext的命名空间,但两者都不是。 第二件事是您无需在函数内编写任何代码,您只需通过种子方法使用SqlCommand创建SQL函数,然后享受您的工作。

 var rslt = await ctx.AssignedInstitutions.Where(e => MainDbContext.IsAssignedIncludedInPickedRoles(e.Roles, "ARIOB")).ToListAsync();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接