我正试图在精巧的时候使用TVP来一次插入几行:
con.Execute(@"
INSERT INTO Author (
FirstName,
LastName,
ParentAuthor
)
SELECT
FirstName,
LastName,
ParentAuthor
FROM @TVP
"
, new[]
{
new Author { FirstName = "Roger", LastName = "Smith", ParentAuthor = 1},
new Author { FirstName = "Stan", LastName = "Smith"},
new Author { FirstName = "Haley", LastName = "Smith"},
new Author { FirstName = "Francine", LastName = "Ling"}
} // .AsTableValuedParameter() => not working
);
但是有没有一种方便的方法将对象集合转换为TableValuedParameter?
答案 0 :(得分:0)
我发现了fast-member,然后就可以这样做了:
var items = new[]
{
new Author {FirstName = "Roger", LastName = "Smith", ParentAuthor = 1},
new Author {FirstName = "Stan", LastName = "Smith"},
new Author {FirstName = "Haley", LastName = "Smith"},
new Author {FirstName = "Francine", LastName = "Ling"}
};
var table = new DataTable();
using (var reader = ObjectReader.Create(
items,
nameof(Author.FirstName),
nameof(Author.LastName),
nameof(Author.ParentAuthor)
))
{
table.Load(reader);
}
con.Execute(@"
INSERT INTO Author (
FirstName,
LastName,
ParentAuthor
)
SELECT
FirstName,
LastName,
ParentAuthor
FROM @TVP
"
, new { TVP = table.AsTableValuedParameter("TVP_Author") }
);
如果有一个类似的功能内置精致,我仍然想知道。