从C#访问数据库存储过程

时间:2015-11-03 16:47:20

标签: c# sql asp.net

我试图访问我的数据库中存在的UserInfo表中的数据。我创建了一个存储过程,在该表上执行select并尝试从我的c#应用程序执行该存储过程。

目前,如果我运行了user,即localhost:12345/user,我会收到500错误。它正在进入我的存储库层,但由于某种原因在遇到using语句时失败了。关于如何解决这个问题的任何想法?

  

错误:500内部服务器错误

控制器

  public class UserController : ApiController
    {
        private readonly IUserBusiness _userBusiness;

        public UserController(IUserBusiness userBusines)
        {
            _userBusiness = userBusines;
        }

        [HttpGet]
        [Route("user")]
        public async Task<ApiResponse<Status, IEnumerable<UserInfo>>> ListUsers()
        {
            return await _userBusiness.ListUsers();
        }
    }

业务层

public class UserBusiness : IUserBusiness
{
    public readonly IUserRepository _userRepository;

    public UserBusiness(IUserRepository userRepository)
    {
        _userRepository = userRepository;
    }

    public async Task<ApiResponse<Status, IEnumerable<UserInfo>>> ListUsers()
    {
        return new ApiResponse<Status, IEnumerable<UserInfo>>(Status.Success, await _userRepository.ListUsersInfo());
    }
}

存储库层

public class UserRepository : IUserRepository
{
    private readonly ISqlQueryProvider _sqlQueryProvider;

    public UserRepository(ISqlQueryProvider sqlQueryProvider)
    {
        _sqlQueryProvider = sqlQueryProvider;
    }

    public async Task<List<UserInfo>> ListUserInfo()
    {
        using (var reader = _sqlQueryProvider.Execute(RepositorySettings.DatabaseConnection, ListUserInfo_Proc, null))
        {
            return reader.Read<ListUserInfo>().ToList();
        }
    }
}

模型

public class UserInfo

{
    public int UserId {get; set;}
    public string Username {get; set;}
    // Properties continue...
}

存储过程

Use DatabaseName;
Go

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE ListUserInfo_Proc
AS
BEGIN
    SET NOCOUNT ON;

    SELECT UserId, UserName -- the list continues
    FROM User
END

0 个答案:

没有答案