[英]Insert into two tables with one table having an auto increment primary key and that same key is used as a foreign key in another table
[英]Insert two records at once into two tables where one table uses the other as foreign key?
我有两个表:
Employee
:EmpId(PK),EmpName。 EmployeeDetails
:Id(自动递增),EmpId(从FK到Employee表),地址,ZipCode。 我正在使用Entity Framework 6。
当我想插入一个新的Employee
,我必须做两次事务,这意味着要使用两次SaveChanges()
才能插入一个新的Employee,然后才将其Id
用作EmployeeDetails
的外键。
一次交易可以做到吗?
谢谢
您可以轻松地一步完成此操作:
using (YourDbContext ctx = new YourDbContext())
{
Employee emp = new Employee();
// set the values for "emp"
emp.EmployeeDetail = new EmployeeDetails();
// set the employee details
ctx.SaveChanges();
}
如果你创建EmployeeDetails
作为的一部分Employee
,你可以节省Employee
单独-与EF将存储两个实体(作为一个“实体图”),并正确设置它们之间的FK约束条件-所有在一个单一的步骤
您应该稍微修改一下模型。 细节是员工的“一部分”。 如果以这种方式创建实体,则在插入员工时,实体框架将为您处理其余工作:
雇员
public class Employee
{
public int EmpId { get; set; }
public string EmpName { get; set; }
public EmployeeDetails EmployeeDetails { get; set; }
}
细节
public class EmployeeDetails
{
public int Id { get; set; }
}
比您可以执行以下操作:
using (dbContext context = new dbContext())
{
Employee emp = new Employee();
emp.EmpName = "John";
emp.EmployeeDetails = new EmployeeDetails
{
//details fields
};
context.SaveChanges();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.