Updated April 11, 2023
Introduction to Entity Framework Insert
Entity Framework is an ORM Framework, which is supported by Microsoft for the .net application. Insert functionality enables the developer to work with the database to insert the data in database. This functionality helps developer to work with the data at higher level of abstraction. Insert comes under the saving feature of Entity framework. It executes the insert command, when program call the “SaveChanges()” method. When any changes occurs to the entity, it executes the insert command to the database.
How to Insert the Data by using Entity Framework?
To insert the data we can use DbSet.Add method so that a new entity is added to a context. This will insert a new record in the database when SaveChanges() method is called.
Code:
Using (var context = new SchoolDBEntities())
{
Var std = new Student()
{
FistName = “Neha”,
LastName = “Shrama”
};
Context.Students.Add(std);
Context.SveChnges();
}
In the above code Context.Students.Add(std) is used to create a new instance of Student entity which is with the context of Added EntityState.
Context.SveChnges() method will build and executes below insert Statement to the database.
Code:
Exec sp_executesql N 'INSERT [dbo].[Students]([FirstName], [LastName])
VALUES (@0,@1)
SELECT [StudentId]
FROM [db].[Students]
WHERE @@ROWCOUNT > 0 AND [StudentID] = scope_identity()', N
''@0 nvarchar(max) ,@1 nvarchar(max) ',@0=Neha ,@1=N’Sharma'
go
Example:
Let us see an example so that it will be clearer how to inset the data.
Suppose we have a record table with the employee details containing Employee ID, Name, City and Designation.
We will see the below code to insert the new record of an employee in the employee table
Code:
private void insertData()
{
TestEntities context = new TestEntities();
// Creating a new employee
Employee objEmployee = new Employee();
objEmployee.name = "Snehal Tiwari";
objEmployee.City = "Mumbai";
ObjEmployee.Designation = "AM";
//Below line of code will add the created employee object to the context.
context.AddToEmployee(objEmployee);
context.SaveChanges();
}
TestEntities is a class, which is given from “Save entity connection setting in web.config”.
Output:
A record of new employee will be added in the first row itself.
DbContext.AddRange() method is used to insert multiple entities at the same time.
DbContext is very import in entity framework. It is a class of entity framework API. We can say it is a carrier or middleware between the database and the domain or entity classes. It is responsible for interaction between the database and class.
It is responsible for below activities:
- Quering: This is responsible for converting LINQ queries to SQL queries and after that, it will send them directly to the database.
- Persisting Data: This deals with the Insert, Update and Delete functions on the database based on their entity states.
- Change Tracking: It will track the changes, which has been occurred on the state of an entity after querying from the database.
- Manage Relationship: It will use CSDL, SSDL and MSL in model first or DbFirst approach. Also, using fluent API configurations in the Code First Approach.
- Caching: It has first level of catching by default. It will store the entities which is retried from context class during the lifetime.
- Object Materialization: It helps in converting a raw data from the database to the object entity.
DbContext Methods:
Below are some DbContext Methods used for inserting the Data:
- Entry: The entry will provide us the access to the change tracking information and entity operations. It will get a DbEntityEntry for the given entity.
- SaveChanges: It will execute the INSERT, DELETE and UPDATE functions to the database for the entities which are added, deleted and modified state.
- SaveChangesAsync: It is a Asynchronous method of the SaveChanges() method.
- Set: This will Creates a DbSet<Entity> which will be used to query the entity and save instances of its entity.
- OnModelCreating: It will take an instance of ModelBuilder. It is called by framework when our context is created first to build the particular model and its mapping in the memory.
Inserting Multiple Record in the Database
Now if we want to insert multiple records we can use it by below code. In the below code we are adding 3 records with their names.
Code:
Var Employee1 = new Employee() { Name = "Neha"}
Var Employee2 = new Employee() { Name = "Summit"}
Var Employee3 = new Employee() { Name = "Sneha"}
Using (var context = new companyContext())
{
Context.Employee.AddRange(dept1, dept2, dept3);
Context.saveChanges();
}
In addition, we can do the same thing by below code. We just need to create a list for the employees
Var Employee1 = new Employee() { Name = "Neha"}
Var Employee2 = new Employee() { Name = "summit"}
Var Employee3 = new Employee() { Name = "Sneha"}
Var employee =new List<Employee>() { Employee1, Employee2, Employee3 };
Using (var context = new CompanyContext())
{
Context.Department.AddRange(employee)
Context.SaveChanges();
}
Output:
After executing the above code, we will get the following output. We assume that table will already have 1 record.
After executing the insert code, it will insert the 3 employee.
Usually the process is very clumsy and bulky earlier. We used to make a connection first so as to open a database first. Then we create a DataSet to fetch the data or to submit the data to the database, to convert data into .NET Objects from DataSet or vice versa so that business rules can be applied. Due to all these bulky and confusing procedures Microsoft came with the framework which is called “Entity Framework”. This will automate the entire database activities for our required application.
Conclusion
In this article, we saw about how we can insert the data into a database using entity framework. We saw how this deals with even if the multiple records need to be inserted. This will reduce and make ease to use in our application.
Recommended Articles
This is a guide to Entity Framework Insert. Here we discuss the introduction, how to insert data by using an entity framework? inserting multiple records. You may also have a look at the following articles to learn more –