EF 6.1标量值函数数据库优先

时间:2014-10-15 06:25:45

标签: c# asp.net-mvc entity-framework sql-function

我的应用程序是c#MVC5,使用EF 6.1。使用Database First导入的表和函数。我可以在DALModel.Store / Stored Procedures / Functions(灰显)下列出的模型(emdx)浏览器中看到该函数。

我正在尝试使用以下功能:

using (var ctx = new DALEntities())
{
    int? result = ctx.fn_TotalClient(MemberRepository.AllowedCId, fromDate, toDate);
    return (result != null ? result.Value : 0);
}

我无法解析fn_TotalClient

非常感谢您的建议。

2 个答案:

答案 0 :(得分:9)

显然我不能直接在我的模型中使用标量值函数;我在此博客中找到了一个解决方案http://programmaticponderings.wordpress.com/2012/11/22/first-impressions-of-database-first-development-with-entity-framework-5-in-visual-studio-2012/

但是,我使用不同的方法将函数重新开发为表值函数,然后使用FirstOrDefault()来获取结果值。

希望这可以帮助面临同样问题的人。

答案 1 :(得分:2)

那么,您需要修改SQL以将单/标量值转换为表值函数,然后才能工作。

  

标量函数原样,它不起作用

CREATE FUNCTION [dbo].[GetSha256]
(
    -- Add the parameters for the function here
    @str nvarchar(max)
)
RETURNS VARBINARY(32)
AS
BEGIN
    RETURN ( SELECT * FROM HASHBYTES('SHA2_256', @str) AS HASH256 );
END -- this doesn't work.
  

标量函数 - >转换为表值函数,它可以工作

CREATE FUNCTION [dbo].[GetSha2561]
(
    -- Add the parameters for the function here
    @str nvarchar(max)
)
RETURNS  @returnList TABLE (CODE varbinary(32))
AS
BEGIN

    INSERT INTO @returnList
    SELECT HASHBYTES('SHA2_256', @str);

    RETURN; -- This one works like a charm.

END