Entity Framework (EF) is an Object Relational Mapper (ORM)
Lets see an example with a simple form which submit user info data in a database by using code first integration
At Visual Studio 2013 or newer
File | New | Project | ASP.NET Web Application
Name: SubmitFormMvcEFcf (SubmitForm with Mvc Entity Framework Code First)
Select a template: MVC
Change Authentication | No Authentication
* Change Authentication | Authentication : Individual User Accounts (entity framework is already installed - you dont have to enable migrations )
Now we have to install Entity Framework. We can do that through the Nuget Package, so right click to the project Name (SubmitFormMvcEFcf) and choose
Manage Nuget Package.
At second tab Online | nuget.org search at Search Online the keyword Entity Framework and install the latest version that you will find VS 2013, At first tab Browse on search write Entity Framework and Install the Lastest stable
Moreover, update all the front end technologies like Bootstrap, Jquery, Jquery Validation and Newtonsoft.Json
Finally to get clear the whole project delete from file Views
Views | Home | About and Contact.cshtml
and from file which is inside Views | Shared | _Layout.cshtml delete the next section
_Layout.cshtml
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home") </li>
<li>@Html.ActionLink("Contact", "Contact", "Home") </li>
</ul>
We start by define our model
After that at folder Models right click and then create a .cs file name as DataUser.cs
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace SubmitFormMvcEFcf.Models
{
public class DataUser
{
public int Id { get; set; }
[Required]
[DisplayName("First name")]
public string FirstName { get; set; }
[Required]
[DisplayName("Last name")]
public string LastName { get; set; }
[Required]
[DisplayName("Telephone")]
public int Telephone { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[EmailAddress]
[DisplayName("Email")]
public string Email { get; set; }
[Required]
[DisplayName("Gender")]
public string Gender { get; set; }
}
}
We will use our already installed by default Home view which is
SubmitFormMvcEFcf | Views | Home | Index.cshtml
We delete everything there is and we add the next section at Index.cshtml.
We use bootstrap to our form
@model SubmitFormMvcEFcf.Models.DataUser
@{
ViewBag.Title = "Home Page";
}
<div class="row">
<div class="col-md-12 col-sm-12 col-lg-12 col-xs-12">
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { role = "form" }))
{
@Html.AntiForgeryToken()
<h4>@ViewBag.Message</h4>
<hr />
@Html.ValidationSummary("", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(m => m.FirstName, new { @class = "control-label" });
@Html.TextBoxFor(m => m.FirstName, new { @class = "form-control" })
</div>
<div class="form-group">
@Html.LabelFor(m => m.LastName, new { @class = "control-label" })
@Html.TextBoxFor(m => m.LastName, new { @class = "form-control" })
</div>
<div class="form-group">
@Html.LabelFor(m => m.Telephone, new { @class = "control-label" })
@Html.TextBoxFor(m => m.Telephone, new { @class = "form-control" })
</div>
<div class="form-group">
@Html.LabelFor(m => m.Email, new { @class = "control-label" })
@Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
</div>
<div class="form-group">
@Html.LabelFor(m => m.Gender, new { @class = "control-label" })
<span>Male:</span>
@Html.RadioButtonFor(m => m.Gender, "male")
<span>Female:</span>
@Html.RadioButtonFor(m => m.Gender, "female")
</div>
<div class="form-group">
<input type="submit" class="btn btn-info" value="Submit" />
</div>
}
</div>
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
[Required]
[DataType(DataType.Password)]
[DisplayName("Password")]
public string CrmPassword { get; set; }
<div class="form-group">
@Html.LabelFor(m => m.CrmPassword, new { @class = "control-label" })
@Html.PasswordFor(m => m.CrmPassword, new { @class = "form-control" })
</div>
In our project with right click we add a folder and we give name as DAL, after that with again right click on file we add a .cs file name as InfoContext.cs
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using SubmitFormMvcEFcf.Models;
namespace SubmitFormMvcEFcf.DAL
{
public class InfoContext : DbContext
{
public InfoContext() : base()
{
}
public DbSet<DataUser> DataUsers { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingEntitySetNameConvention>();
}
}
}
We continue with our Controller to take control between our model and the form we want to submit a user's data.
So next we add the next code part to our Controller which in that case in HomeController.cs
SubmitFormMvcEFcf | Controllers | HomeController.cs
using System.Web.Mvc;
using SubmitFormMvcEFcf.DAL;
using SubmitFormMvcEFcf.Models;
namespace SubmitFormMvcEFcf.Controllers
{
public class HomeController : Controller
{
private InfoContext db = new InfoContext();
public ActionResult Index()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(DataUser model)
{
if (!ModelState.IsValid)
{
return View(model);
}
db.DataUsers.Add(model);
db.SaveChanges();
return View("ThankYou");
}
public ActionResult ThankYou()
{
return View();
}
}
}
After that we add the View of ThankYou page by the next steps.
Right click inside View() and click Add View.. continue by press Add the make sure the name of View is ThankYou
@{
ViewBag.Title = "ThankYou";
}
<h2>ThankYou</h2>
<p>
Thank you
</p>
The last step is to configure our web.config file and before we enable our Entity Framework
At Web.config we insert above <appSettings> the next section
<connectionStrings>
<add name="InfoContext" connectionString="Data Source=YourServerName;Initial Catalog=InfoContext;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>
Before you do anything else Clean you project and rebuild it. At Package Manager Console we add
Enable-Migrations
and after that write
Add-Migration
The point with code first is that any change you do at your model then you update your database by press
Update-Database but before this you must maek true at Configuration.cs
the AutomaticMigrationsEnabled AutomaticMigrationsEnabled = true;
You can insert dummy data through Configuration.cs
Insert the next test code to your application
using SubmitFormMvcEFcf.Models;
namespace SubmitFormMvcEFcf.Migrations
{
using System.Data.Entity.Migrations;
internal sealed class Configuration : DbMigrationsConfiguration<SubmitFormMvcEFcf.DAL.InfoContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(SubmitFormMvcEFcf.DAL.InfoContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
context.DataUsers.AddOrUpdate(
p => p.FirstName,
new DataUser { Id = 123456, FirstName = "Dimitris", LastName="Kokkinakis",Telephone = 2102531331, Email="tzitzokokkinak@hotmail.com",Gender = "Male"}
);
}
}
}
Update-Database
If we add a new property at our model then we press Update-Database but if we want to delete it we press Update-Database -Force
Test our Controller with PostMan
Because we useAntiForgeryToken, both to Index.cshtml and the DataAnnotation to Index at HomeController.cs,
PostMan would not response to our Post so we can to put in comments.
After that we use POST method to url: http://localhost:11961/Home/Index Home is the controller Index the method we call.
At Body in x-www-form-urlencoded we add the next key-value matches.