我有以下 2 个表:
public class TestA
{
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable<TestB> Test { get; set; }
}
public class TestB
{
public int Id { get; set; }
public int TestAId { get; set; }
}
我的想法是我可以从我的 TestA 对象访问与 TestA 相关的所有 TestB 记录。我想弄清楚的是如何插入测试 A 和测试 B,尤其是当测试 B 有多行与测试 A 相关时。这是我尝试过的:
var data = new TestA
{
Name = "ABC",
Id = 1,
Test = new List<TestB>
{
new TestB() { Id = 1, TestAId = 1},
new TestB() {Id = 2, TestAId = 1},
new TestB() {Id = 3, TestAId = 1}
}
};
var query = "INSERT INTO TestA(Id, Name) VALUES(@Id, @Name) INSERT INTO TestB(Id, TestAId) VALUES(@Test.TestB.Id, @Test.TestB.TestAId)";
using (var con = conn)
{
con.Execute(query, data);
}
我知道我们可以给 dapper 一个列表,它足够智能来枚举该列表并插入单独的记录,但是如果该列表是对象的子项,我该如何完成同样的事情?我尝试让我的值也成为 @Test.Id, @Test.TestAId
但它有完全相同的错误。
The member of type Test.TestB cannot be used as a parameter value
最佳答案
你能试试这个吗:
var data = new TestA
{
Name = "ABC",
Id = 1,
Test = new List<TestB>
{
new TestB() { Id = 1, TestAId = 1},
new TestB() {Id = 2, TestAId = 1},
new TestB() {Id = 3, TestAId = 1}
}
};
var query = "INSERT INTO TestA(Id, Name) VALUES(@Id, @Name) INSERT INTO TestB(Id, TestAId) VALUES(@Test.TestB.Id, @Test.TestB.TestAId)";
using (var con = conn)
{
var query = "INSERT INTO TestA(Id, Name) VALUES(@Id, @Name)";
con.Execute(query, new { Id = data.Id, Name = data.Name });
foreach (var item in data.Test)
{
string processQuery = "INSERT INTO TestB(Id, TestAId) VALUES (@Id, @TestAId )";
connection.Execute(processQuery, item);
}
}
关于sql - 使用 Dapper 将子列表插入 SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46877530/