Code First Approach in ASP.NET CORE MVC

0

 How to implement Code First Approach in ASP.NET CORE MVC:-


Code First Approach is best for light-weight and smaller project in ASP.NET MVC Core, it is basically created to those developer who is not know about SQL. without SQL Server or any database package developer can create complete project.



Step 1 New Project

Once you have installed the Visual Studio 2019 and .Net Core 3.1 SDK, you can start building a new ASP.NET Core Application.


Step 2nd:-

Create a web app and From the Visual Studio select Create a new project. Select ASP.NET Core Web Application > Next.


Step 3rd:-

Give your project a name i.e. SampleCodeFirstExample and give your project a location where it’ll be saved and click Create.


Step4th:-

 Install the NuGet Packages

From the Solution right click on dependency, select Manage NuGet Packages and Select the Browse tab, and then enter Microsoft.EntityFrameworkCore.SqlServer in the search box, select Latest Stable Version and Install.


Step5h:-


Now, install Microsoft.EntityFrameworkCore.Tools as same as above steps.


Step6th:-


Create Model and Context Classes:

Now, Add new class with name “Emp”, using Right-click the Models folder and select Add Class.


public class Emp

    {

        public long empid { get; set; }

        public string empname { get; set; }

        public int salary { get; set; }


        public string designation { get; set; }


    }



Step7th:-


Right-click the Models folder and select Add > Class. Name the class MyDbContext and click Add and change code in MyDbContext.cs as following:


  public class MyDbContext:DbContext

    {

        public MyDbContext(DbContextOptions<MyDbContext> options):base(options)

        {


        }

        public DbSet<Emp> emps { get; set; }

    }



Step8th:-


Connection string you need to write inside the appsetting.json file as follows:


 "ConnectionStrings": {

    "Conn": "Data Source=SHIVA-PC\\SQLEXPRESS;Initial Catalog=collegeerp;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;"

  },


Step9th:-


Register Connection String under Program.cs file



Step10th:-


builder.Services.AddDbContext<MyDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("Conn")));



Step11th:-


Create Database using Migration Commmand


add-migration initialmigration



Step12th:-


Write update database command


update-database



Step13


We can check MS-SQL Server and Check Database 


Step14th:-


Add new column in table then add new property in model class


public int age{get;set;}


Step15:-

write followings commands for migration

add-migration addedColumnname

update-database assedColumnname




Post a Comment

0Comments

POST Answer of Questions and ASK to Doubt

Post a Comment (0)