ive尝试在网上搜索并在过去的几个小时内编写一些代码,但是没有运气。我得到了一些我无法使用的代码示例,或者代码无法正常工作,所以我想这是stackoverflow时间:)
长话短说,我的问题对C#和Dapper来说是相当新的,并且想知道我如何从数据库中检索给定的ID?假设我要求输入ID 1,瞧,它返回ID1。同样,在检索ID时是否可以在ID上要求说一个名字,例如id.name?
我还有很多其他方法需要写,但是我想我会问这个,然后希望我看到光后就可以写其余的方法。
谢谢。
我的存储过程如下:
CREATE PROCEDURE getAccessHelper
@ID int
AS
BEGIN
SET NOCOUNT ON;
SELECT * FROM dbo.AccessHelper WHERE ID = @ID
END
GO
我的acceshelper类如下:
namespace SCAM_MVC.Models.AccessHelper
{
public class AccessHelper
{
public Dictionary<string, string> Fields { get; set; }
public int Id { get; set; }
public string Name { get; set; }
public string Plugin { get; set; }
public string ProjectName { get; set; }
public AccessHelper(int id, string name, string plugin, string projectName)
{
Plugin = plugin;
Name = name;
Id = id;
ProjectName = projectName;
}
}
}
我尝试的方法如下:
public void GetAccessHelper(int id)
{
using (SqlConnection sqlCon = new SqlConnection("Data Source = SQL01; Initial Catalog = SCAM; Integrated Security = True"))
{
var accessHelper = sqlCon.Query<AccessHelper>("getAccessHelper", new { id = id }, commandType: System.Data.CommandType.StoredProcedure);
}
}
我知道id = id
是错的,但这是我的最新尝试。
答案 0 :(得分:1)
您的AccessHelper(int id)方法不返回任何内容,因为它是无效的。我建议您使其返回一个AccessHelper对象,如下所示:
public AccessHelper GetAccessHelper(int id)
{
using (SqlConnection sqlCon = new SqlConnection("Data Source = SQL01; Initial Catalog = SCAM; Integrated Security = True"))
{
var accessHelper = sqlCon.Query<AccessHelper>("getAccessHelper", new { id = id }, commandType: System.Data.CommandType.StoredProcedure);
}
return accessHelper ;
}
然后可以获取所需的accessHelper实例的名称;例如:
var ah = this.GetAccessHelper(2); //2 refers to the id you want
name = ah.Name;