0

以下脚本创建一个Person对象并将这些值插入 SQL Server 数据库

 $(document).ready(function ()
        {
            var person = {};
            person.FirstName = "Bill";
            person.LastName = "Wilson";

            $('#button').click(function ()
            {
                var sender = JSON.stringify({ 'p': person });
                $.ajax(
                {
                    type: "POST",
                    url: "GetDrugQuiz.asmx/InsertPerson",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: sender,
                    success: function (data)
                    {
                        console.log(data.d);
                    },
                    error: function (xhr, ajaxOptions, thrownError)
                    {
                        console.log(xhr.status);
                        console.log(thrownError);
                    }
                });
            });

        });

-

  [WebMethod]
            public void InsertPerson(Person p)
            {
                //var jss = new JavaScriptSerializer();

                string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
                using (var con = new SqlConnection(cs))
                {
                    using (var cmd = new SqlCommand("spInsertNames", con))
                    {
                        con.Open();
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@firstName",p.FirstName);
                        cmd.Parameters.AddWithValue("@lastName", p.LastName);
                        cmd.ExecuteNonQuery();
                    }
                }
            }

如果我只有一个人要插入,这很好用。但是假设用户有能力创建几个 Person 对象,我想一次插入它们。这样做的最佳方法是什么?我试过:

 $(document).ready(function ()
        {
            var person = {};
            person.FirstName = "Bill";
            person.LastName = "Wilson";

            personArray = new Array();
            var person2 = {};
            person2.FirstName = "Tim";
            person2.LastName = "Thompson";
            personArray.push(person);
            personArray.push(person2);
            var dto = { 'personList': personArray }

            $('#button').click(function ()
            {
                //this is printing to the console correctly
                console.log(dto);
                $.ajax(
                {
                    type: "POST",
                    url: "GetDrugQuiz.asmx/InsertPersonList",
                    dataType: "json",
                    data: JSON.stringify(dto),
                    success: function (data)
                    {
                        alert('success!');
                        alert(data.d);
                    },
                    error: function (xhr, ajaxOptions, thrownError)
                    {
                        alert(xhr.status);
                        alert(thrownError);
                    }
                });
            });

        });

[WebMethod]
        public void InsertPersonList(List<Person> personList)
        {
            string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
            //var jss = new JavaScriptSerializer();
            //I know at some point the JSON will have to be deserialized
            foreach (var person in personList)
            {
                using (var con = new SqlConnection(cs))
                {
                    using (var cmd = new SqlCommand("spInsertNames",con))
                    {
                        con.Open();
                        cmd.Parameters.AddWithValue("@firstName", person.FirstName);
                        cmd.Parameters.AddWithValue("@lastName", person.LastName);
                        cmd.ExecuteNonQuery();
                    }
                }
            }
        }

这失败并出现错误System.InvalidOperationException: InsertPersonList Web Service method name is not valid. at System.Web.Services.Protocols.HttpServerProtocol.Initialize() at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing)

我知道,即使我尝试过的方法是可能的,这也不是一个好主意。我也知道我必须以某种方式将 JS 数组反序列化为 Person 对象列表。解决这个问题的最佳方法是什么?目前我用于插入Names表的存储过程是

create proc spInsertNames
 @firstName varchar(50)
,@lastName varchar(50)
as
begin
insert into Names(FirstName, LastName)
values (@firstName,@lastName)
end

(这就是我尝试 foreach 循环的原因,因为这些值是使用行构造函数插入的)。似乎我应该使用 DataTable 来选择 SQL 中的表变量。我在标记附近吗?

4

1 回答 1

2

您可以使用 DataTable 将您的集合插入到表值参数(与表变量不同)中。

CREATE TYPE dbo.NameList AS TABLE
(
  FirstName NVARCHAR(255), 
  LastName  NVARCHAR(255)
);

然后你的程序:

CREATE PROCEDURE dbo.InsertNames_ByTVP
  @Names AS dbo.NameList READONLY
AS
BEGIN
  SET NOCOUNT ON;

  INSERT dbo.Names(FirstName, LastName)
    SELECT FirstName, LastName FROM @Names;
END
GO

您的 C# 代码将简单地传递 DataTable:

SqlCommand cmd = new SqlCommand("dbo.InsertNames_ByTVP", connection_object);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter names = cmd.Parameters.AddWithValue("@Names", DataTableName);
names.SqlDbType = SqlDbType.Structured;
cmd.ExecuteNonQuery();
于 2013-08-28T20:03:56.750 回答