Monday 19 August 2013

Entity Framework Code-First Approach

Visual Studio 2010 brought new approaches to modeling for Entity Framework 4.1.

1.     Code First
2.     Model First
3.     Database first

Code First: In Code First approach, you avoid working with visual model designer (EDMX) completely.You write your POCO classes first and then create database from these POCO classes. Developers who follow the path of Domain-Driven Design (DDD) principles prefer to begin by coding their classes first and then generating the database required to persist their data. One important thing to understand is that there are two new types introduced for Code First approach, DbContext and DbSet. DbContext is a simplified alternative to ObjectContext and is the primary object for interacting with a database using a specific model. DbSet(Of TEntity) is a simplified alternative to ObjectSet(Of TEntity) and is used to perform CRUD operations against a specific type from the model in Code First approach.

Prerequisites:
Basic knowledge of .Net Framework3.5, C#, Visual Studio 2010 and MS SQL Server is required.
Also, basic knowledge of entity framework is preferred.

So let’s learn about code first step by step..

What is Code-First?:
Entity Framework introduced Code First approach from Entity Framework 4.1. Code First is mainly useful in Domain Driven Design In the Code First approach, you can focus on the domain design and start creating classes as per your domain requirement rather than design your database first and then create the classes which matches your database design. Code First APIs will create the database on the fly based on your entity classes and configuration.

So as a developer, you first start writing C#/VB.net classes rather than focusing on database design and then when you
run the application, Code First APIs will create the new database or map your classes with existing database before
running your application.

Let’s see simple code first example

Let’s create first simple code first example.

1- Create New MVC3 Project with Razor ViewEngion. 
2- Add a New Model Class named User.cs in Models Directory .
3- Add the Properties Defined Below :

          [Key]
        public int UID { get; set; }
        public string UserName { get; set; }
        public string PAssword { get; set; }

4- Now, create context class which is derived from DBContext class with one DbSet properties, for User.
       public class Context : DbContext
    {
        public Context()
            : base("mycon")  //mycon is the ConnectionString, it is Optional
        {

        }
        public DbSet<User> Users { get; set; }
    }
 5- the ConnectionString are 
     <add name="mycon" connectionString="data source=./SQLExpress; database=myCodeFirstDB; User ID=sa; Password=sa123;" providerName="System.Data.SqlClient"/>

 6- Now goto HomeController.cs 
     move to Index.cshtml of HomeController and create a Login Page as below described :

@model CodeFirstApproach.Models.User

 @using (Html.BeginForm("Index", "Home"))
{
   <div>
        <fieldset>
            <legend>Account Information</legend>

            <div>
            @Html.LabelFor(m=>m.UserName)
            </div>
            <div>
            @Html.TextBoxFor(m => m.UserName)
            </div>
                        <div class="editor-label">
                @Html.LabelFor(m => m.PAssword)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(m => m.PAssword)
            </div>
            <div><input type="submit" value="Save" id="btn1" name="btn1" /></div>
            </fieldset></div>
}

7- Now Add the below Code in your Home Controller.cs File for Creating Table and Saving Data.
     
        [HttpPost]
        public ActionResult Index(User _usr)
        {
            using (var ctx = new Context())
            {
                User stud = new User() { UserName = _usr.UserName, PAssword= _usr.PAssword };
                ctx.Users.Add(stud);
                ctx.SaveChanges();
            }
            return View();
        }
Now run your Application it looks like :
Enter UserNAme and Password and Click on Save Button. Your Data will be Saved in the Specified Database in ConnectionString. when you Run your Application first time Table will be Created Automatically if not Exist.

Download Complete Project Demo Click here with CRUD operation.


0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives