System.Data.Entity.Infrastructure.DbRawSqlQuery`1 [System.Int32]'键入'System.IConvertible错误

时间:2015-08-01 16:09:03

标签: c# sql-server entity-framework

我正在尝试创建新记录并不断收到错误

  

System.Data.Entity.Infrastructure.DbRawSqlQuery`1 [System.Int32]'键入'System.IConvertible

我有这段代码..

// Contact
c.Name = IsItNull(contact.Name);
int newContactID = AddContact(c);

AddContact方法是

public int AddContact(Contact contact)
    {
        return Convert.ToInt32(AWJE.Database.SqlQuery<int>
            ("usp_InsertContact @Name", contact.Name));
    }

storedproc是

    CREATE PROCEDURE [dbo].[usp_InsertContact]
    @ContactID int output,
    @Name nvarchar(50)
AS
SET NOCOUNT OFF
SET TRANSACTION ISOLATION LEVEL READ COMMITTED

DECLARE @ERROR_SEVERITY int,
        @MESSAGE varchar(1000),
        @ERROR_NUMBER int,
        @ERROR_PROCEDURE nvarchar(200),
        @ERROR_LINE int,
        @ERROR_MESSAGE nvarchar(4000);

begin try
    insert into [Contact]
    (Name) values (@Name)
    set @ContactID = @@IDENTITY
end try

BEGIN CATCH
    SET @ERROR_SEVERITY = ISNULL(ERROR_SEVERITY(),'');
    SET @ERROR_NUMBER = ISNULL(ERROR_NUMBER(),'');
    SET @ERROR_PROCEDURE = ISNULL(ERROR_PROCEDURE(),''); 
    SET @ERROR_LINE = ISNULL(ERROR_LINE(),'');
    SET @ERROR_MESSAGE = ISNULL(ERROR_MESSAGE(),'');

    -- Test if the transaction is uncommittable.
    IF (XACT_STATE()) = -1
        BEGIN
            --PRINT N'The transaction is in an uncommittable state. Rolling back transaction.'
            ROLLBACK TRANSACTION;
        END;

    -- Test if the transaction is active and valid.
    IF (XACT_STATE()) = 1
        BEGIN
            --PRINT N'The transaction is committable. Committing transaction.'
            COMMIT TRANSACTION;   
        END;

    SET @MESSAGE = 'Error Occured in Stored Procedure ' + cast(@ERROR_PROCEDURE as varchar(200)) + 
                    '; Line Number ' + cast(@ERROR_LINE as varchar) + 
                    '; Message: [' + cast(@ERROR_NUMBER as varchar) + '] - '
                    + cast(@ERROR_MESSAGE as varchar(255))

    RAISERROR(@MESSAGE, @ERROR_SEVERITY, 1);
END CATCH;

GO

错误在

处抛出
int newContactID = AddContact(c);

我究竟做错了什么?我看过其他SO帖子,这有点类似于这个错误,但他们是关于Linq,没有像我这样做。 有任何想法吗?

1 个答案:

答案 0 :(得分:2)

我发现了问题,问题出在AddContact方法

public int AddContact(Contact contact)
{
    return Convert.ToInt32(AWJE.Database.SqlQuery<int>
        ("usp_InsertContact @Name", contact.Name));
}

我没有使用SqlQuery,而是在其位置使用了ExecuteSqlCommand并修复了错误。所以现在这个方法看起来像这样..

return AWJE.Database.ExecuteSqlCommand
    ("usp_InsertContact @Name", contact.Name);