如何在C#中在SQL Server中发送数组/集合

如何在C#中在SQL Server中发送数组/集合,c#,asp.net,sql,ado.net,sqlcommand,C#,Asp.net,Sql,Ado.net,Sqlcommand,它工作正常,可以在我的第一个表中插入值 SqlCommand command = new SqlCommand("INSERT INTO Author (LastName, FirstName, MiddleName,BirthDate)VALUES(@LastName, @FirstName, @MiddleName,@BirthDate);SELECT SCOPE_IDENTITY()", _connection); command.Parameters.AddWithValue("@Las

它工作正常,可以在我的第一个表中插入值

SqlCommand command = new SqlCommand("INSERT INTO Author (LastName, FirstName, MiddleName,BirthDate)VALUES(@LastName, @FirstName, @MiddleName,@BirthDate);SELECT SCOPE_IDENTITY()", _connection);
command.Parameters.AddWithValue("@LastName", LastNameTextBox.Text);
command.Parameters.AddWithValue("@FirstName", FirstNameTextBox.Text);
command.Parameters.AddWithValue("@MiddleName", MiddleNameTextBox.Text);
command.Parameters.AddWithValue("@BirthDate", BirthDateTextBox.Text);
string authoriD = command.ExecuteScalar().ToString();
这里有个问题,我解决不了

SqlCommand commandB = new SqlCommand("INSERT INTO Book(AuthorID,Book,Genre,Pages)VALUES(@AuthorID,@Book,@Genre,@Pages)", _connection);
commandB.Parameters.AddWithValue("@AuthorID", authoriD);

for (int i = 0; i < AddBooks.BookTextBoxValue.Count; i++)
{
    commandB.Parameters.AddWithValue("@Book", AddBooks.BookTextBoxValue[i]);
}

foreach (string itemgenre in AddBooks.GenreTextBoxValue)
{
    commandB.Parameters.AddWithValue("@Genre", itemgenre);
}

foreach (string itempages in AddBooks.PagesTextBoxValue)
{
    commandB.Parameters.AddWithValue("@Pages", itempages);
}

commandB.ExecuteNonQuery();
SqlCommand commandB=new-SqlCommand(“插入图书(authord、图书、流派、页面)值(@authord、@Book、@Genre、@Pages)”,\u连接);
commandB.Parameters.AddWithValue(“@AuthorID”,AuthorID);
for(int i=0;i
对于每一位作者,他/她写的书都有体裁,等等。。。所以你应该只有一个for循环。 您的代码流应该是这样的:

for(...)
{
//insert into Book (author, book, genre, pages)
}
您的图书作者字段是作者表的外键。一个作者可以有许多书面书籍,因此您的Book表必须为一个作者提供多个条目。您的图书表应包含以下内容(按作者、图书、流派、页面的顺序):

  • 你,MyNewBook,Genre1,10
  • 你,MyOldBook,Genre2,20
  • 你,MyNotSoNewBook,Genre1100
  • 你,MyVeryNiceBook,Genre11000

您应该为每个循环执行一次插入操作。我的usercontrol有3个文本框,BookAdd.ascx.cs我为每个文本框设置了public StringCollection。但问题是我无法理解如何创建SqlCommand,因为我不知道将有多少书,1、2、3。。。等当有人添加新作者时,他/她可以添加一本或多本书,当按下“保存”按钮时,我需要保存我的新作者,带上他的id和他的书。如何在没有硬代码的情况下添加永久性的书籍计数。嗨@nickshp,我今年很少访问stackoverflow。但是,即使你找到了一些办法,我也要回答你的问题。要解决这个问题,您需要跟踪每个作者添加的图书数量。可以通过获取表单控件的row/line count属性并在for循环的条件中使用该值来实现这一点。