Microservices Part 2

In the previous article, we have seen the overview of EF Core and the steps to create SQL DB in Azure.
https://anuphosur.wordpress.com/2020/03/29/microservices-part-1/

In the part 2 of the Micro-services series, we are going to discuss about basic of EF Core.

Let’s create a new Project of type asp.net core web api. Choose name as per your convenience . Throughout the series, I’ll be working on Employee management system. I will create a project name as EmployeeManagement.Api.

After creating a Project, please add below Nuget Packages
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.Tools

Note: I’m using the latest version of .net core(3.1.0).

I assume that you already have an experience/knowledge on the asp.net core web api/ understanding on the http verb, controller etc. If not, I would recommend you to go through the below article.
https://docs.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-3.1

Firstly, let’s create simple Employee class.

public class Employee

    {

        public int Id { get; set; }

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public int PhoneNumber { get; set; }

        public string EmailId { get; set; }

        public double Salary { get; set; }

    }

In the above model class, we have simple getter/setter properties and there are nothing special about it.

Secondly, let’s create a class called EmployeeContext

public class EmployeeContext:DbContext

    {

        public EmployeeContext(DbContextOptions dbContextOptions):base(dbContextOptions)

        {

        }

        public DbSet Employees { get; set; }

    }

I would say, DbContext class is the heart of EF Core. DbContext can be used to query and save instances of your entities in the database; moreover, it’s a combination of Repository and Unit of work pattern. We’ll discuss about these pattern in the future articles.

DbSet is an abstract class. It is used to return the result from the database, however, it may not reflect changes made in the context that have not been persisted to the database.

DbContext Methods

Method

Usage

Add Adds a new entity to DbContext with Added state and starts tracking it. This new entity data will be inserted into the database when SaveChanges() is called.
AddAsync Asynchronous method for adding a new entity to DbContext with Added state and starts tracking it. This new entity data will be inserted into the database when SaveChangesAsync() is called.
AddRange Adds a collection of new entities to DbContext with Added state and starts tracking it. This new entity data will be inserted into the database when SaveChanges() is called.
AddRangeAsync Asynchronous method for adding a collection of new entities which will be saved on SaveChangesAsync().
Attach Attaches a new or existing entity to DbContext with Unchanged state and starts tracking it.
AttachRange Attaches a collection of new or existing entities to DbContext with Unchanged state and starts tracking it.
Entry Gets an EntityEntry for the given entity. The entry provides access to change tracking information and operations for the entity.
Find Finds an entity with the given primary key values.
FindAsync Asynchronous method for finding an entity with the given primary key values.
Remove Sets Deleted state to the specified entity which will delete the data when SaveChanges() is called.
RemoveRange Sets Deleted state to a collection of entities which will delete the data in a single DB round trip when SaveChanges() is called.
SaveChanges Execute INSERT, UPDATE or DELETE command to the database for the entities with Added, Modified or Deleted state.
SaveChangesAsync Asynchronous method of SaveChanges()
Set Creates a DbSet that can be used to query and save instances of TEntity.
Update Attaches disconnected entity with Modified state and start tracking it. The data will be saved when SaveChanges() is called.
UpdateRange Attaches a collection of disconnected entities with Modified state and start tracking it. The data will be saved when SaveChanges() is called.
OnConfiguring Override this method to configure the database (and other options) to be used for this context. This method is called for each instance of the context that is created.
OnModelCreating Override this method to further configure the model that was discovered by convention from the entity types exposed in DbSet properties on your derived context.

DbContext Properties

Method

Usage

ChangeTracker

Provides access to information and operations for entity instances this context is tracking.

Database

Provides access to database related information and operations for this context.

Model

Returns the metadata about the shape of entities, the relationships between them, and how they map to the database.

In the StartUp.cs, let’s modify the below changes

public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDbContext(options =>
{
options.UseSqlServer(Configuration.GetConnectionString(“DefaultConnection”));
});
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseHttpsRedirection();

app.UseRouting();

app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}

ConfigureServices method is used to add services to the container during runtime; whereas, configure method is used to configure the http request pipeline.

In the app settings.json, I have provided the connection string of the Azure SQL.

Now time has come to reflect the changes from Domain class to the database by using migration.

Add Migration:

If you are running on Dotnet cli
dotnet ef migrations add

In case, you are running on Nuget manager package console
Add-migration

Update changes to the Database:

Dot net Cli:
dotnet ef database update

Nuget manager package console
Update-database

Now the Employee table has to created in the database.

Now let’s create a EmployeeController class.

[Route(“api/[controller]”)]
public class EmployeeController : ControllerBase
{
private readonly EmployeeContext _employeeContext;
public EmployeeController(EmployeeContext employeeContext)
{
_employeeContext = employeeContext;
}
// GET: api/values
[HttpGet]
public IEnumerable GetAllEmployees()
{
return _employeeContext.Employees;
}

// GET api/values/5
[HttpGet(“{id}”)]
public Employee GetEmployee(int id)
{
return _employeeContext.Employees.FirstOrDefault(x => x.Id == id);
}

// POST api/values
[HttpPost]
public IEnumerable InsertEmployee([FromBody]Employee employee)
{
_employeeContext.Employees.Add(employee);
_employeeContext.SaveChanges();
return _employeeContext.Employees;
}

// PUT api/values/5
[HttpPut]
public IEnumerable UpdateEmployee([FromBody]Employee employee)
{
_employeeContext.Employees.Update(employee);
_employeeContext.SaveChanges();
return _employeeContext.Employees;
}

// DELETE api/values/5
[HttpDelete(“{id}”)]
public IEnumerable DeleteEmployee(int id)
{
var employee = _employeeContext.Employees.FirstOrDefault(x => x.Id == id);
if (employee != null)
{
_employeeContext.Employees.Remove(employee);
_employeeContext.SaveChanges();
}
return _employeeContext.Employees;
}
}

Now let’s build the application and Run.

Let’s navigate to url/api/Employee and we can see there are no data in the database.

Open Postman and perform the post operation using the below data
Screenshot 2020-03-30 at 12.28.29 AM
The result is visible in the response section of the postman app but wait, the application is allowing the email id as empty and phone number & salary are getting defaulted to 0.

Suppose Email Id has to be made mandatory and Phone number & Salary should be equal to 0 then what we are suppose to do?

We need to use Data Annotation in fixing these issues and we’ll look into that in the future article.

Have a nice day!

One thought on “Microservices Part 2

  1. Pingback: Microservices part 3 – Articles on latest .net technology

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s