How i will create DbContext class & connect with Database server?

Step_01:

First of all create a Model. Suppose a class name CoffeeModel.

namespace RootCRUDAPI.Models
{
	public class CoffeeModel
	{
		public int Id { get; set; }
		[Required(ErrorMessage = "Please Enter Title.")]
		public string Title { get; set; }
		[Required(ErrorMessage = "Please Enter Description.")]
		public string Description { get; set; }
		public DateTime CreatedDate { get; set; } = DateTime.Now;
	}
}

Then, create DbContext class name with your app name. Suppose you are developing Coffee App. now your context class will be CoffeeDbContext.
now create properties of your class. The final Code will be:

namespace RootCRUDAPI.Data
{
	public class CoffeeDbContext: DbContext
	{
		public CoffeeDbContext(DbContextOptions<CoffeeDbContext> options):base(options)
		{

		}

		public DbSet<CoffeeModel> coffeeModels { get; set; }
	}
}

Here, CoffeeModel is a class which properties name coffeeModels.

N.B: please note that here will be shown error becasue you need to add some Nuget package manager. Here are some list of manager which you should added
1. Microsoft.EntityFrameworkCore.
2. Microsoft.EntityFrameworkCore.Design.
3. Microsoft.EntityFrameworkCore.SqlServer.
4. Microsoft.EntityFrameworkCore.Tools.

Step_02:

Now we will add ConnectionStrings for connection our model with Database server.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost;Database=joyDB;User=sa;Password=MyPass@word;TrustServerCertificate=True;" //localhsot database server
  }
}

If you have hosting server then you will change this connection string same as below:

“DefaultConnection”: “Server=xyz; Database=lxebliib_test;User=lxebliib_user;Password=1234;TrustServerCertificate=True;”

Here xyz are hosting domain name and 1234 are database password.

Step_03:

After setup connection string, now add this code above of var app = builder.Build(); line.

//add
builder.Services.AddDbContext<CoffeeDbContext>(options => options.UseSqlServer(
    builder.Configuration.GetConnectionString("DefaultConnection")
));

Steip_04:

Now we will running some command for creating Table in our database.
1. Open Terminal
2. Type cd then type your projectname and press enter.
3. Type dotnet ef migrations add initialcreate and press enter.
4. Type dotnet ef database update and press enter.

Finally CoffeeModel Table will be generate in our database. Next we will enter some data in our database.

755 thoughts on “How i will create DbContext class & connect with Database server?