In my previous blog post ASP.NET Core with Entity Framework, demonstrated how to implement entity framework core with database first approach in ASPE.NET Core web API. here we will see how to integrate entity framework core with code first approach.
Using Entity Framework Core in ASP.NET Core Web API
Getting StartedThe code first approach can be used in both cases (already have database or database does not exist while designing). Entity Framework has a context that manages the interaction between those classes and your database.
It could use that model to create a database if you wanted to and also update the database if the model changes, using a feature called First Migrations.
The Code First approach adds a model builder that inspects your classes that the context is managing, and then uses a set of rules or conventions to determine how those classes and the relationships describe a model, and how that model should map to your database. All of this happens at runtime. You'll never see this model, it's just in memory.
Here we will demonstrate the following points:
- Create Web API in Visual Studio 2019 step by step.
- Download entity framework core library.
- Create database context (Dbcontext).
- Create a model class.
- Download entity framework core provided library.
- Configure entity framework core SQL provider.
- Interaction with database table in web API controller.
Develop Web API in ASP.NET Core
- Open Microsoft Visual Studio.
- Click on Create a new Project.
- Enter Web API in the search box.
- Select the ASP.NET Core Web API template and select Next.
- In the Configure your new project dialog, name the project StudentManager and select Next.
- In the Additional information dialog:
- Confirm the Framework is .NET 6.0 (Long-term support).
- Confirm the checkbox for Use controllers (uncheck to use minimal APIs) is checked.
- Click on Create
Download Entity Framework Core Library
- Go to your Solution Explorer.
- Right click on the solution Explorer.
- Click on the NuGet Package Manager.
- Type entity framework in the search box of Browse tab.
- List if libraries will be listed, select Microsrt.EntityFrameworkCore.
- Click on the Install button on the right side of the pan.
Create .Net Core Dbcontext
- Create a new class in the project and name it DataContext and open the class file.
- Copy the below code and replace with the class inside the class file.
public class DataContext:DbContext
{
public DataContext(DbContextOptions<DataContext> options):base(options){}
DbSet<tblStudent> Students;
}
In the above code the DbContextOptions, is an internal API that supports the Entity Framework Core infrastructure and not subject to the same compatibility standards as public APIs. It may be changed or removed without notice in any release. You should only use it directly in your code with extreme caution and knowing that doing so can result in application failures when updating to a new Entity Framework Core release.
The DbSet in code represents the collection of all entities in the context, or that can be queried from the database, of a given type. DbSet objects are created from a DbContext using the DbContext.Set method.
Create a Model Class
The tblStudent is an entity framework model class which is represented to the student table in database. Below are the codes of model class. Create a new class with the same name and replace the below code.
public class tblStudent
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public string Name { get; set; }
public string RollNo { get; set; }
}
.Net Framework Data Provider Download
This Microsrt.EntityFrameworkCore.SqlServer database provider allows Entity Framework Core to be used with Microsoft SQL Server including Azure SQL Database. The provider is maintained as part of the Entity Framework Core Project. The following steps is to download the provided from NueGet.
- Go to your Solution Explorer.
- Right click on the solution Explorer.
- Click on the NuGet Package Manager.
- Type entity framework in the search box of Browse tab.
- List if libraries will be listed, select Microsrt.EntityFrameworkCore.SqlServer.
- Select the version that is compatibility for your current framework on the right side of the pan. I have installed 6.0.23 version as it is compatible with .net 6.0, which is I am using in this demonstration.
- Click on the Install button on the right side of the pan.
Configure entity framework core SQL provider.
The is the second last steps to implement entity framework core in ASP.NET core API. Follow the below steps to configure entity framework core SQL provider. Open the program file and past the below code before invoking the build method of web application builder.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"Dbcontext": "Server=NQMUMLAP0151;Initial Catalog=FMN;User ID=webusers;Password=webusers"
}
}
Then open the program file and past the below code before invoking the build method of web application builder.
builder.Services.AddDbContext<DataContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("ConnectionStrings")));
Your code should be placed like below code.
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<DataContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("ConnectionStrings")));
var app = builder.Build();
Interaction with database table in web API controller.
The following code in side the controller, describes how to interact with databbase table using entity framework core.
[ApiController]
[Route("api/[controller]")]
public class Student : ControllerBase
{
private readonly DataContext dataContext;
public Student(DataContext dbContext)
{
_logger = logger;
this.configuration = configuration;
this.dataContext = dbContext;
}
[HttpPost("saveStudent")]
public string Save(tblStudent tblStudent)
{
try
{
this.dataContext.Students.Add(tblStudent);
this.dataContext.SaveChanges();
return "Save successfully";
}
catch (Exception ex)
{
return "Failed to Save";
}
}
[HttpPost("getStudents")]
public IEnumerable<tblStudent>GetStudents()
{
return this.dataContext.Students;
}
[HttpPost("getStudent")]
public IEnumerable<tblStudent> GetStudent(int id)
{
return this.dataContext.Students.Where(s=>s.ID==id);
}
}
Summary
I hope end of this demonstration, this blog post helped you to learn how to use entity framework core in ASP.NET Web API.
Thanks