简体   繁体   中英

Insert two records at once into two tables where one table uses the other as foreign key?

I have two tables:

  • Employee : EmpId (PK), EmpName .
  • EmployeeDetails : Id (auto increment), EmpId (FK to Employee table), Address, ZipCode .

I'm using Entity Framework 6.

When I want to insert a new Employee , I must do two transactions, meaning use SaveChanges() twice, in order to insert a new employee and only then use its Id as a foreign key in EmployeeDetails .

Is is possible to do that in one transaction ?

Thanks

You can easily do this in a single step:

using (YourDbContext ctx = new YourDbContext())
{
    Employee emp = new Employee();
    // set the values for "emp"

    emp.EmployeeDetail = new EmployeeDetails();
    // set the employee details

    ctx.SaveChanges();
}

If you create the EmployeeDetails as part of the Employee , you can just save the Employee alone - and EF will store both entities (as an "entity graph") and set up the FK constraints between them properly - all in a single step

You should modify your model a bit. Details is "part" of Employee. If you create the entities in this way, when you insert an employee, entity framework will take care of the rest for you:

Employee

public class Employee
{
    public int EmpId { get; set; }

    public string EmpName { get; set; }

    public EmployeeDetails  EmployeeDetails { get; set; }
}

Details

public class EmployeeDetails
{
    public int Id { get; set; }
}

Than you can do this:

using (dbContext context = new dbContext())
{
    Employee emp = new Employee();

    emp.EmpName = "John";
    emp.EmployeeDetails = new EmployeeDetails 
    {
        //details fields
    };

    context.SaveChanges();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM