代码之家  ›  专栏  ›  技术社区  ›  Jez

在LINQ to Entities查询中调用自定义标量DB函数?

  •  7
  • Jez  · 技术社区  · 8 年前

    有没有一种方法可以调用自定义标量DB函数作为LINQ到实体查询的一部分?我在网上唯一能找到的就是这个页面:

    https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/ef/language-reference/how-to-call-custom-database-functions

    然而,这里给出的说明似乎假设您使用的是DB-first方法,并讨论修改 .edmx 文件如果您使用的是代码优先的方法呢?我希望能够写出这样的东西:

    var result = await (
        from itm in _itemDataContext.Items
        where
            itm.QryGroup1 == "Y" &&
            _itemDataContext.Dbo_MyCustomScalarIntFn(itm.QryGroup2) > 0
    ).ToArrayAsync();
    
    2 回复  |  直到 8 年前
        1
  •  3
  •   Jez    8 年前

    事实证明,这个功能并没有内置到实体框架中,所以我不得不使用NuGet包( CodeFirstFunctions )要获得它:


    IItemDataContext

    [DbFunction("CodeFirstDatabaseSchema", "fn_IsCorrectProduct")]
    bool Fn_IsCorrectProduct(string companyID, string itemCode);
    

    ItemDataContext

    [DbFunction("CodeFirstDatabaseSchema", "fn_IsCorrectProduct")]
    public bool Fn_IsCorrectProduct(string companyID, string itemCode)
    {
        // UDF is described in DbFunction attribute; no need to provide an implementation...
        throw new NotSupportedException();
    }
    
        2
  •  1
  •   Rui Estreito    8 年前

    我认为您可以使用ExecuteSqlCommand,但您必须对针对BD执行的sql进行硬编码,如下所示:

    var result = await (
        from itm in _itemDataContext.Items
        where
            itm.QryGroup1 == "Y" &&
            _itemDataContext.Database.ExecuteSqlCommand("Exec yourFunction "+itm.QryGroup2) > 0
    ).ToArrayAsync();
    

    我没有测试,但应该可以解决你的问题。