微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 无法使用Entity Framework 6获取存储过程结果

我有一个存储过程,它返回0或1,具体取决于我的数据库中是否存在指定的电子邮件地址:

CREATE PROCEDURE [DatabaseSchema].[EmailAddressIsDuplicate] (@emailAddress nvarchar(255))
AS
BEGIN
    SET NOCOUNT ON;

    IF EXISTS(
        SELECT *
        FROM [DatabaseSchema].[EmailUpdatesRegistrant]
        WHERE EmailAddress = @emailAddress
    )
        RETURN 1
    ELSE
        RETURN 0

    RETURN 0
END

GO

我试图从Entity Framework 6数据库上下文中获取此存储过程的结果:

using (DatabaseContext dbContext = new DatabaseContext())
{
    ObjectParameter param = new ObjectParameter("emailAddress",typeof(bool));
    var result = dbContext.EmailAddressIsDuplicate(emailAddress); 
}

我收到很多错误.

错误#1:使用上面的代码,var结果始终设置为-1.

错误#2:我尝试导航到编辑函数导入并将返回集合设置为布尔标量值.这会引发以下错误

The data reader returned by the store data provider does not have enough columns for the query requested.

错误#3:我回去并将编辑功能导入返回值设置为无.然后我尝试了以下代码

using (DatabaseContext dbContext = new DatabaseContext())
{
    var p = new sqlParameter("@emailAddress",emailAddress);
    var result = dbContext.Database.sqlQuery<bool>("DatabaseSchema.EmailAddressIsDuplicate",p);
}

没有立即错误抛出,但我不知道我是否可以从var结果中获取有用的数据.尝试将结果转换为bool会引发以下错误

Cannot convert type ‘System.Data.Entity.Infrastructure.DbRawsqlQuery’ to ‘bool’

关于如何查看此存储过程(0或1)的结果的任何想法?

解决方法

您可以尝试在存储过程签名中添加输出参数(@result):

CREATE PROCEDURE [DatabaseSchema].[EmailAddressIsDuplicate]
    (@emailAddress nvarchar(255),@result bit out)
AS
BEGIN
    SET NOCOUNT ON;

    IF EXISTS(SELECT *
              FROM [DatabaseSchema].[EmailUpdatesRegistrant]
              WHERE EmailAddress = @emailAddress)
       SET @result = 1
    ELSE
       SET @result = 0

    RETURN @result
END
GO

(您必须相应地重新定义您的EF模型函数定义)

using (DatabaseContext dbContext = new DatabaseContext())
{
    ObjectParameter isDuplicate = new ObjectParameter("isDuplicate",typeof(bool)); 
    var result = dbContext.EmailAddressIsDuplicate(emailAddress,isDuplicate);

    bool emailIsDuplicate = (bool)isDuplicate.Value;.    
}

如果要使用out参数直接调用存储过程,可以遵循以下建议:
Database.SqlQuery calling stored procedure that has multiple output parameters

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐