Monday 23 April 2018

Simple set up of Entity Framework Core Web Application


This tutorial will guide you through setting up a simple application in ASP.Net Core 2.0 with entity framework. Within minutes, you can configure a simple CRUD model  and build your application on top of that. 

Step 1 : Setting up 

Fire up your Visual Studio IDE ( assuming you have configured the Core 2.0 in your IDE, If not this link would help )  and create a ASP.Net Core Web application. The Authentication selection should be "No Authentication"


Add Following Nuget Packages to your project 

PM>Install-Package Microsoft.EntityFrameworkCore.SqlServer

PM>Install-Package Microsoft.EntityFrameworkCore.Tools

PM>Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design

Step 2 : Add the model class and the context class 

Then Create a sample model as follows in the Models folder

public class Student
    {
        [Key]
        public int StudentId { get; set; }

        [Display(Name = "Student Name")]
        [Required]
        [StringLength(50)]
        public string Name { get; set; }

        [Display(Name = "Address")]
        [StringLength(100)]
        public string Address { get; set; }

        [Display(Name = "Age")]
        [Range(5,18)]
        public int Age { get; set; }

    }

Then we need to add a context class which is inherited from the DBContext class as follows. 

public class StudentContext : DbContext
    {
        public StudentContext(DbContextOptions<StudentContext> options)
            : base(options)
        { }

        public DbSet<Student> Students { get; set; }
    }

Then we need to configure the Startup class to retrieve the connection string from the appsettings.json and load the DBContext class using dependency injection as follows. 

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            var connectionString = Configuration.GetConnectionString("DBConnectionString");
            services.AddDbContext<StudentContext>(options => options.UseSqlServer(connectionString));
      
        }

Step 3 : Create the database using db migrations 

The next step is to create the Database using code-first model with entity framework. Build your project and make sure that there are no build errors. 

Open up the Package manager console and initiate your migration script using following command. 

PM> Add-migration InitStudent

It should create the Migrations folder in your ode structure and the initial migration file as follows.

protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "Students",
                columns: table => new
                {
                    StudentId = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                    Address = table.Column<string>(maxLength: 100, nullable: true),
                    Age = table.Column<int>(nullable: false),
                    Name = table.Column<string>(maxLength: 50, nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Students", x => x.StudentId);
                });
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "Students");
        }

Next, you need to update the database using following command ( use package manager console ). 

PM>Update-Database

Check your database and there should be a new table ( Students ) added to your DB. 

Step 3 : Scaffolding the Student Controller and Views  

As the nest step , we are going to generate the Controller class and relevant views for Student entity. We do not need to manually code all those but , generate using scaffolding.


Right click on your Controllers folder and select "New Scaffold Item". Select the MVC Controller with views, using Entity Framework.  You have to select the appropriate Model class and the Data Context class as in following picture. 


If everything goes well, The Controller and relevant CRUD views should be created. 

Execute your application using the IDE run tool or use the Dotnet run command. Now you will be able to run the web app successfully. To create a link to your newly created entity, go to the _Layout.html partial view in the Shard folder and change it as follows.

<li><a asp-area="" asp-controller="Students" asp-action="Index">Students</a></li>
 
Now you should be able to perform all CRUD operations to Student entity. 


You can get the source code from this git repo.

No comments:

Post a Comment