I have 2 tables like below. am using DB first approch
public class Team
{
public long Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
public class Employee
{
public long Id { get; set; }
public long TeamId { get; set; } // foreign key reference fom Team table
public string Name { get; set; }
public long ReferedBy { get; set; } // foreign key reference fom employee table
}
now i have to insert data to both table once. for example i need to insert data like below.
before introducing Referred By column i was using below code to insert.
Team team = new Team();
team.Name = "Team1";
team.Description = "Some Description";
Employee E1 = new Employee();
E1.Name = "Jon";
Employee E2 = new Employee();
E2.Name = "Harish";
team.Employee.Add(E1);
team.Employee.Add(E2);
DBEntity db = new DBEntity();
db.Set<Team>().add(team);
db.saveChanges();
after introducing Referred By Column how i can insert these reference to database.
If you need to execute the insertion as bulk insert and the id of the Employee table is an identity column, you have to call the SaveChanges() twice to get the identity value from db so that you set emp2.ReferredBy=emp1.id;
If your requirement to hit the db in one hit, you have two options 1. Use a transaction and call SaveChanges twice where a failure occurs the transaction roll back. 2. Build your own identity technique and stop identity in db.