检索对象 [Dapper 的存储过程]

在过去的几个小时里,我试图在网上搜索并编写一些代码,但没有运气。要么我得到了一些我无法使用的代码示例,要么代码不起作用,所以我猜是 stackoverflow 时间了:)


长话短说,我的问题对 C# 和 Dapper 来说还很陌生,想知道我如何从我的数据库中检索给定的 ID?假设我要求 id 1,瞧它返回 id 1。同样,当我检索它时,是否可以要求让我们在 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, 是错误的,但这是我最近的尝试。


慕盖茨4494581
浏览 213回答 1
1回答

守着一只汪

您的 AccessHelper(int id) 方法不返回任何内容,因为它是无效的。我建议你让它返回一个 AccessHelper 对象,如下所示:public AccessHelper GetAccessHelper(int id)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; using (SqlConnection sqlCon = new SqlConnection("Data Source = SQL01; Initial Catalog = SCAM; Integrated Security = True"))&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var accessHelper = sqlCon.Query<AccessHelper>("getAccessHelper", new { id = id }, commandType: System.Data.CommandType.StoredProcedure);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;return accessHelper ;&nbsp; &nbsp; }然后,您可以获得所需的 accessHelper 实例的名称;例如 :var ah = this.GetAccessHelper(2); //2 refers to the id you want&nbsp;name = ah.Name;
打开App,查看更多内容
随时随地看视频慕课网APP