我认为一个好的方法是将您的类序列化为 XML 并将它们传递给 SQL。对于服务器部分,开始的路径是:
create table Books (BookID int identity, Title varchar(50), Rating int);
create table Chapters (BookID int, Title varchar(50), Sequence int);
go
create procedure AddBook
@book xml
as
begin
insert Books (Title, Rating)
select
n.value('@Title', 'varchar(50)'),
n.value('@Rating', 'int')
from
@book.nodes('/Book') x(n);
declare @bookID int;
set @bookID = scope_identity();
insert Chapters (BookID, Title, Sequence)
select
@bookID,
n.value('@Title', 'varchar(50)'),
n.value('@Sequence', 'int')
from
@book.nodes('/Book/Chapters/Chapter') x(n);
end;
go
declare @data xml;
set @data = '
<Book Title="New Book" Rating="9">
<Chapters>
<Chapter Title="Chapter 1" Sequence="1" />
<Chapter Title="Chapter 2" Sequence="2" />
<Chapter Title="Chapter 3" Sequence="3" />
</Chapters>
</Book>'
exec AddBook @data;
select * from Books;
select * from Chapters;
结果:
BookID Title Rating
----------- -------------------------------------------------- -----------
1 New Book 9
(1 row(s) affected)
BookID Title Sequence
----------- -------------------------------------------------- -----------
1 Chapter 1 1
1 Chapter 2 2
1 Chapter 3 3
(3 row(s) affected)
并且不要忘记将过程语句打包在事务中。