In this tutorial let us look at how to add a record, add multiple records to the database. Before inserting records into the database, we must add the entities to the context first. To do that we use the Add
& AddRange
methods. Once the records are added to the context, we can call the SaveChanges
method, which sends the insert query to the database. The EF also takes care of updating identity values generated in the database in the entity. We also show you how to add related entities or data.
Source Code:
The source code of this project available in GitHub.
Table of Contents
Add Single Record
The code below creates a new instance of the Department
object. Then it uses the Add
method of the DbSet
to add the newly created Department
entity to the DbContext
. Note that the Add
method adds the new entity in Added
State. Finally, we call the SaveChanges
method to insert the new Department
record into the database.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | public void AddSingleRecord() { //Adding using (EFContext db = new EFContext()) { db.Database.Log = Console.WriteLine; Department dep = new Department(); //Create a new department dep.Name = "Secuirty"; db.Departments.Add(dep); //Add it to the Context db.SaveChanges(); //Call Save Changes Console.WriteLine("Department {0} ({1}) is added ", dep.Name, dep.DepartmentID); } Console.ReadKey(); } |
The DepartmentID
is an identity field. The database generates its value when we insert the record into the database. The EF retrieves the newly inserted value of DepartmentID
and updates the DepartmentID
in the entity. This will keep the entity in sync with the database.
The SQL Query of the above method is as follows. Note the select statement, which retrieves the DepartmentID
1 2 3 4 5 6 7 8 | INSERT [dbo].[Departments]([Name], [Descr]) VALUES (@0, NULL) SELECT [DepartmentID] FROM [dbo].[Departments] WHERE @@ROWCOUNT > 0 AND [DepartmentID] = scope_identity() |
Whenever we add an entity using the Add
or AddRange
method, the context marks the state of the entity as added
. Hence when we call the SaveChanges
Context will create an insert query and sends it to the database.
AddRange
You can add multiple records or multiple objects using the AddRange
method of DbSet
as shown in the following code. The code creates a list of department
objects and inserts two new departments
to the list. We add the list to the context using the AddRange
method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | using (EFContext db = new EFContext()) { db.Database.Log = Console.WriteLine; List<Department> deps = new List<Department>(); deps.Add(new Department { Name = "Dept1", Descr = "" }); deps.Add(new Department { Name = "Dept1", Descr = "" }); db.Departments.AddRange(deps); db.SaveChanges(); Console.WriteLine("{0} Departments added ", deps.Count); Console.ReadKey(); } |
The EF will save only those records, which you add to the context using the Add
method or AddRange
method.
For Example, consider the following example. We retrieve all the Departments
into the deps
List. We create two more Departments
(Dept3
& Dept4
) and add it the deps
list. In the next line, we add the Dept5
using the Add
method.
This code only inserts the Dept5
to the database. The Dept3
& Dept4
are not added as EF is not aware of them as they are not added to the context.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | public void AddListOfOjects1() { //This wont add using (EFContext db = new EFContext()) { db.Database.Log = Console.WriteLine; List<Department> deps = new List<Department>(); //These records are not added deps.Add(new Department { Name = "Dept3", Descr = "" }); deps.Add(new Department { Name = "Dept4", Descr = "" }); //This record is added db.Departments.Add(new Department { Name = "Dept5", Descr = "" }); db.SaveChanges(); Console.WriteLine("{0} Departments added ", deps.Count); Console.ReadKey(); } } |
The Context will track only those entities, which it retrieves from the database. It also tracks those entities which you add to the context using Add
or AddRange
methods. Hence it tracks all entities which are in the deps
collection as they came from the database using. db.Departments.ToList()
. But later we added two more departments to deps
directly. The Context is not aware of these new records. Hence when the context calls SaveChanges
, it does not create an Insert query for them.
Now, consider the following scenario. First, we retrieve all the Departments
into the deps
List. The List contains 6 records. We add two more records making it 8 records. Now we use the AddRange
method and then call the SaveChanges
method
The SaveChanges
inserts 8 records to the database. Although the six records already exist in the database. The Add
or AddRange
does not check if the records exist or not. They just create a new entity and inserts them into the context and make their status as Added
, which results in an insert query when you invoke SaveChanges
Entity Framework always ignores the value you provide in the Identity column. It does not include it in the insert query.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | public void AddListOfOjects2() { //This wont add using (EFContext db = new EFContext()) { db.Database.Log = Console.WriteLine; //The deps contain 6 records List<Department> deps = db.Departments.ToList(); //Two more records are added deps.Add(new Department { Name = "Dept3", Descr = "" }); deps.Add(new Department { Name = "Dept4", Descr = "" }); //All of them added db.Departments.AddRange(deps); db.SaveChanges(); Console.WriteLine("{0} Departments added ", deps.Count); Console.ReadKey(); } } |
It is a very common scenario that you may want to add related entities. There are few ways you can do that.
The following example code creates a new Employee
. It then creates a new Department
. The newly created Employee
is added to the Employees
Navigation property.
Now, when we add the new dep
to the context using the Add
method it also adds the Employee
automatically. Hence SaveChanges
will insert a new employee and department to the database.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | public void AddRelatedData1() { // Adding Department & Employee using (EFContext db = new EFContext()) { db.Database.Log = Console.WriteLine; //Create new employee Employee emp = new Employee(); emp.FirstName = "Anil"; emp.LastName = "Kumble"; // Creat a new department Department dep = new Department(); dep.Name = "Bowling"; dep.Employees = new List<Employee>(); dep.Employees.Add(emp); //Add dep to Departments //Note that we are not adding Employee. The employee is already added to Dep. db.Departments.Add(dep); //Save db.SaveChanges(); Console.WriteLine("Department {0} ({1}) is added ", dep.Name, dep.DepartmentID); Console.WriteLine("Employee {0} ({1}) is added in the department {2} ", emp.FirstName, emp.EmployeeID, emp.Department.Name); Console.ReadKey(); } } |
Or in this case, we add two employees to Dep
and then add the Department
to the Context.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | public void AddRelatedData2() { // Adding Department & Employee using (EFContext db = new EFContext()) { db.Database.Log = Console.WriteLine; // Creat a new department Department dep = new Department(); dep.Name = "Bowling"; dep.Employees = new List<Employee>(); dep.Employees.Add(new Employee { FirstName = "Anil", LastName = "Kumble" }); dep.Employees.Add(new Employee { FirstName = "Harbajan", LastName = "Singh" }); //Add dep to Departments //Note that we are not adding Employee. Employee is already added to Dep db.Departments.Add(dep); //Save db.SaveChanges(); Console.WriteLine("Department {0} ({1}) is added ", dep.Name, dep.DepartmentID); Console.ReadKey(); } } |
Connected & Disconnected Scenario
In the last tutorial, we discussed persistence in the entity framework. The connected or disconnected scenario has no role to play while adding an entity to the context. Because we need to use the Add
& AddRange
to insert them into the context, Hence they automatically become connected to context.
References
Read More
- Save Changes in Entity Framework
- EntityStates in Entity Framework
- Add Records/ Add Multiple Records in Entity Framework
- Update Record in Entity Framework
- Deleting Records in Entity Framework
Let us say that the Employee class has a Boss property, so the Employee table describe a hierarchy. I want to use AddRange to add employee A and employee B. The boss of A is B and B have a boss who is already in the table. How EF will handle this? If A is added first then there is a foreign key violation. If I have hundreds of new employees can EF figure out the correct insert order?
thank you very much
I really needed this artic