Insert data into multiple table in entity framework

entity-framework entity-framework-6 model-view-controller

Question

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.

enter image description here

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.

1
1
7/6/2016 10:31:09 AM

Popular Answer

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.

Check Get identity before SaveChanges

0
5/23/2017 12:16:16 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow