我使用的是2.6.88版本的NPoco微ORM。
假设我有一个这样的类层次结构:
[NPoco.TableName("Person")]
[NPoco.PrimaryKey("PersonID", AutoIncrement = false)]
class Person
{
public Guid PersonID { get; set; }
public String Name { get; set; }
}
class Employee : Person
{
public String Department { get; set; }
}我需要将这个类层次结构映射到一个使用“每个子类的表”方法设计的数据库。这意味着我有一个包含列PersonID和Name的Person表,以及一个包含列PersonID和Department的Employee表。
现在我的问题是如何使用NPoco将新员工插入到数据库中?我尝试了这样的东西:
Employee myEmployee = new Employee() { PersonID = Guid.NewGuid(), Name = "Employee Name", Department = "TestDepartment" };
NPoco.Database myDb = new NPoco("MyConnection");
using (var transaction = myDb.GetTransaction())
{
myDb.Insert<Person>(myEmployee as Person);
myDb.Insert<Employee>("Employee", "PersonID", false, myEmployee);
transaction.Complete();
}这段代码在第一次插入时失败,因为NPoco试图将特定于Employee的字段插入Person表。
我如何正确地实现这一点?
发布于 2015-03-13 05:11:25
如果您使用的是NPoco,则通过调用myDb.GetTransaction();开始一个事务,并使用transaction.Complete();提交一个事务,但不是以代码中反映的方式提交。
修改代码后,您可以使用:
using (var transaction = myDb.GetTransaction())
{
myDb.Insert<Person>(person);
var sql = new Sql("INSERT INTO Employee (Department,PersonId) VALUES(@0, @1)", employee.Department, employee.PersonId );
myDb.Execute(sql);
transaction.Complete();
}或者在Employee表中添加一个Name列,然后使用以下命令插入新的Employee
using (var transaction = db.GetTransaction())
{
myDb.Insert<Person>(person);
myDb.Insert<Employee>("Employee", "PersonId", false, employee);
transaction.Complete();
}https://stackoverflow.com/questions/28968163
复制相似问题