Crud Operation in MVC 5 With Entity Framework and Kendo UI
This article describes, how to perform basic CRUD operations in an MVC5 application using Entity Framework 6 and Kendo UI.
We will use following Kendo UI components
1. Kendo Grid to show all Employee details.
2. Kendo window to Perform add and Edit operations.
Create Domain Model using Database First workflow
Step 1. Create a database and some table.
Open SSMS and using visual designer create a database , name it as Organization and create two tables called Employee and Department. If you are not a fan of visual designer and prefer SQL script to generate Database and tables, then copy and paste below code as a new query and run the script.
Step 2.Go to visual studio and create a new project , Name it as DatabaseFirstDemo
• Open visual studio.
• Go to Files ---->New---->Project
• Under New Project window select Web application.
• Give the project a name (KendoGridCrud)
• Click Ok
Create new ApplicationCreate Empty MVC Application
Step 3.Install Entity Framework.
With the new project the first step is to Install EF. To do that , we use package manager console.
Package Manager Console
• Go to Tools.
• Select Nuget Package Manger and Then Package Manager Console.
• Install Entity Framework using the install-package command.
Install-Package EntityFramework -Version6.2.0
EF installed successfully message
Step 4. Add Ado.Net Entity Data Model.
• Right Click on the Models folder of your project.
• Add ----> Add New Item.
• Under Add new Item window select Data tab and under that select Ado.Net Entity Data Model and click Add.
Add New ItemAdo.Net Entity Data Model
This is going to be our conceptual Model that represents the mapping between our database tables and domain classes. I have given it a meaningful name as OrganizationModel.
• Under the Entity Data Model wizard, select EF Designer From database , cause we already have a database and click next.
Entity Data Model Wizard
• In the next window select or specify the connection to your database.
1. Specify Server Name
2. Choose Database.
3. Test the connection and
4. Click Ok.
Entity Data Model Wizard
• Change the connection name to OrganizationDbContext and click on Next.
Connection Name
• In the next window select your table and give the model namespace a meaningful name as OrganizationModel and click finish.
Notice :- At this point EF looks at our database and displays the tables, views , stored procedure and Functions , currently we only had tables so we just ticked the table and left the rest as is.
data objects and settings window
At this point , you will get a security warning like "Running this template can harm your computer" , don't worry about it and just click next. It gives us the warning because visual studio tries to run a template to generate the code.
OrganizationModel.edmx diagram
Unfolding Edmx
unfolding edmx
EF generates domain models by running some templates, these templates are present under an edmx file, the extension of templates is .tt. Let's uncover these templates. As you Notice in the above figure, we have two templates.
1. OrganizationModel.Context.tt and
2. OrganizationModel.tt
Here the "tt" stands for template , the first template is responsible for generating DbContext and DBSet while the second template is responsible for generating our domain Entities.
This is the reason when you expand the first template that is your context.tt you will find your DbContext class, similarly on expanding Model.tt you will find all your domain Entities.
Edmx overview
expand context.tt
expand model.tt
DbContext Class
At this point, if we expand our context class, we see the actual generated code. This is a plain C# code that EF generates for us. This class derives from the DbContext, so we call it our context class.
Remember DbContext is an abstraction over the database. It provides a simple API to load the data from a database or save data to the database.
It has properties of type DbSet. A DbSet represents a Table in our Database. As in our database we had two tables Employee and Department, EF generated two Dbset namely DbSet of Employee and DbSet of Department.
DbContext
Domain Classes
On expanding the other template that is model.tt we can see our domain Entities. Each domain Entities has properties based on our table columns.
Department Class generated by EF
Employee class generated by EF
Create methods for Create, Read, Update and Delete operations
publicclassHomeController:Controller{//// GET: /Home/publicActionResultIndex(){returnView();}publicActionResultGetEmployees(DataSourceRequest req){OrganizationDbContext db =newOrganizationDbContext();
List<GridVM> gvms =newList<GridVM>();
gvms =(from a in db.Employeesjoin b in db.Departments
on a.DepartmentId equals b.IdselectnewGridVM{
Id=a.Id,
Name= a.Name,
Salary=a.Salary,
Department= b.Name
}).ToList();returnJson(gvms.ToDataSourceResult(req), JsonRequestBehavior.AllowGet);}publicvoidAddEmployee(Employee emp){OrganizationDbContext db =newOrganizationDbContext();
db.Employees.Add(emp);
db.SaveChanges();}publicvoidUpdateEmployee(Employee emp){OrganizationDbContext db =newOrganizationDbContext();Employee objToUpdate = db.Employees.Find(emp.Id);
objToUpdate.Name = emp.Name;
objToUpdate.Salary = emp.Salary;
objToUpdate.DepartmentId = emp.DepartmentId;
db.Entry(objToUpdate).State = EntityState.Modified;
db.SaveChanges();}publicvoidDeleteEmployee(Employee emp){OrganizationDbContext db =newOrganizationDbContext();Employee objToDelete = db.Employees.Find(emp.Id);
db.Employees.Remove(objToDelete);
db.SaveChanges();}}
Create a ViewModel for Grid
publicclassGridVM{publicint Id {get;set;}publicstring Name {get;set;}publicint? Salary {get;set;}publicstring Department {get;set;}}