Entity Framework Core For Beginners In Asp.Net Core – Code First Approach



Published On Monday June 29, 2020 Reading Time: 6 minutes

What is Orm?

Object-Relational Mapper (ORM) is a technique that lets you query and manipulates data from a database using an object-oriented paradigm. ORM is the technique of being able to write queries like SQL Queries, as well as much more complicated ones, using the object-oriented paradigm on a preferred programming language. As for the particular post, I am going to discuss on Entity Framework Core on a .Net Core Project.

Entity Framework Core:

Entity Framework Core (EF Core) is the latest version of the Entity Framework from Microsoft. As per the official document from Microsoft – Entity Framework (EF) Core is a lightweight, extensible, open-source, and cross-platform version of the popular Entity Framework data access technology. EF Core can serve as an object-relational mapper (O/RM), enabling .NET developers to work with a database using .NET objects, and eliminating the need for most of the data-access code they usually need to write.

Support For Database Engines:

EF Core being extensible, it supports a number of database engines which make the use of the EF core broader.

  • SQL Server 2012 onwards
  • SQLite 3.7 onwards
  • EF Core in-memory database
  • Azure Cosmos DB SQL API
  • PostgreSQL
  • MySQL, MariaDB
  • Oracle DB 11.2 onwards

The above-listed database engines are some of the many engines supported by EF Core.

For the demonstration, I will be using an Asp.Net Core 3.1 Web API Project. The project will be a simple Addressbook for contact management.

NuGetPackage associated with the tutorial:

  1. Microsoft.EntityFrameworkCore
  2. Microsoft.EntityFrameworkCore.SqlServer
  3. Microsoft.EntityFrameworkCore.Tools
  4. System.ComponentModel.Annotations

Folder Structure:

Entity Framework Core For Beginners In Asp.Net Core - Code First Approach Folder Structure

To start with the project create a default API application in .Net Core 3.1, now add two class library

  1. WebApi.DataAccess.EntityFrameworkCore: Handles database operation with EF Core
  2. WebApi.Shared: Stores Classes to be accessed within the entire application

Project Reference:

The core project needs to reference both the class library WebApi.DataAccess.EntityFrameworkCore, WebApi.Shared. The Class library WebApi.DataAccess.EntityFrameworkCore need to have a reference of WebApi.Shared.

NuGet Package Installation:

You can see the above image for the reference as well but the major installation that needs to be done is:

WebApi.DataAccess.EntityFrameworkCore Class Library

  1. Microsoft.EntityFrameworkCore
  2. Microsoft.EntityFrameworkCore.SqlServer
  3. Microsoft.EntityFrameworkCore.Tools

WebApi.Shared Class Library

  1. System.ComponentModel.Annotations

WebApi

  1. Microsoft.EntityFrameworkCore.Tools
  2. Swashbuckle.AspNetCore (Optional)

 

Let’s get started with the WebApi.Shared Class Library

Create a folder named Model and add a class Contact.cs

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace WebApi.Shared.Model
{
    public class Contact
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)] //For Identity Column With Unique Values
        public string Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Address { get; set; }
        public string MobileNo { get; set; }
    }
}

Now, let’s make the use of WebApi.DataAccess.EntityFrameworkCore Class Library

Add a folder named DataModel, add a class named ApplicationDbContext.cs

using Microsoft.EntityFrameworkCore;
using WebApi.Shared.Model;

namespace WebApi.DataAccess.EntityFrameworkCore.DataModel
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
        {
        }
        public DbSet<Contact> ContactDetails { get; set; }
    }
}

The ApplicationDbContext is the main class that makes the connection with the database and used for entity declaration and operations.

We now come to the core application WebApi

Appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=XXXXXX;Database=XXXXXX;uid=XX;pwd=XXXXXXXX;"
  }
}

The connection string is the node added in the appsettings.json, just replace the connection string in the DefaultConnection value.

Startup.cs

using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
using WebApi.DataAccess.EntityFrameworkCore.DataModel;

namespace WebApi
{
    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)
        {
            //Register Db Context For Entity Framework Core
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddControllers();

            //Optional For Swagger
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("V1", new OpenApiInfo
                {
                    Title = "ORM Implementation",
                    Version = "V1",
                    Description = "Api Description",
                    TermsOfService = new Uri("https://rashik.com.np"),
                    Contact = new OpenApiContact
                    {
                        Name = "Company Name",
                        Email = "info@email.com",
                        Url = new Uri("https://rashik.com.np"),
                    },
                    License = new OpenApiLicense
                    {
                        Name = "ORM Implementation License",
                        Url = new Uri("https://rashik.com.np"),
                    }
                });
            });
        }

        // 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();
            }

            //Optional For Swagger
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/V1/swagger.json", "Integrating ORM");
            });

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

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

The above is how my startup.cs class looks like. The swagger UI code is optional in both the methods ConfigureServices and Configure.

 

//Register Db Context For Entity Framework Core 
    services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

The above code is the only one required if you want to go straight into the EF Core tutorial. The code registers the ApplicationDbContext Class from  WebApi.DataAccess.EntityFrameworkCore Class Library as the DbContext Class with the connection string to be got from appsettings.json with the node of DefaultConnection.

Create a controller inside the controller folder with the name AddressBookController.cs

using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WebApi.DataAccess.EntityFrameworkCore.DataModel;
using WebApi.Shared.Model;

namespace WebApi.Controllers
{
    [Route("api/addressbook")]
    [ApiController]
    public class AddressBookController : ControllerBase
    {
        private readonly ApplicationDbContext _applicationDbContext;

        public AddressBookController(ApplicationDbContext applicationDbContext)
        {
            _applicationDbContext = applicationDbContext;
        }

        /// <summary>
        /// Get All List In Address Book
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("getListContacts")]
        public async Task<List<Contact>> GetAllContacts()
        {
            return await _applicationDbContext.ContactDetails.ToListAsync();
        }


        /// <summary>
        /// Get Contact Details By First Name
        /// </summary>
        /// <param name="firstName"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("getContactByFirstName/{firstName}")]
        public async Task<List<Contact>> GetContactByFirstName(string firstName)
        {
            var contactDetails = await _applicationDbContext.ContactDetails.Where(x => x.FirstName == firstName).ToListAsync();
            return contactDetails;
        }


        /// <summary>
        /// Add Contact Details To Address Book
        /// </summary>
        /// <param name="contact"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("addContactDetails")]
        public async Task<HttpResponseMessage> AddContactDetails(Contact contact)
        {
            var response = new HttpResponseMessage(HttpStatusCode.NotFound);

            await _applicationDbContext.ContactDetails.AddAsync(contact);
            var result = await _applicationDbContext.SaveChangesAsync();
            if (result > 0)
            {
                response.StatusCode = HttpStatusCode.OK;
            }
            else
            {
                response.StatusCode = HttpStatusCode.BadRequest;
            }
            return response;
        }


        /// <summary>
        /// Update Contact Details Based In Id
        /// </summary>
        /// <param name="contact"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("updateContactDetails")]
        public async Task<HttpResponseMessage> UpdateContactDetails(Contact contact)
        {
            var response = new HttpResponseMessage(HttpStatusCode.BadRequest);
            var contactDetails = _applicationDbContext.ContactDetails.FirstOrDefault(x => x.Id == contact.Id);
            if (contactDetails != null)
            {
                contactDetails.FirstName = contact.FirstName;
                contactDetails.LastName = contact.LastName;
                contactDetails.Address = contact.Address;
                contactDetails.MobileNo = contact.MobileNo;
            }
            var result = await _applicationDbContext.SaveChangesAsync();
            if (result > 0)
            {
                response.StatusCode = HttpStatusCode.OK;
            }
            return response;
        }

        /// <summary>
        /// Remove A Contact Details By Id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("removeContactDetails/{id}")]
        public async Task<HttpResponseMessage> RemoveContactDetails(string id)
        {
            var response = new HttpResponseMessage(HttpStatusCode.BadRequest);
            Contact contact = new Contact{Id = id};
            _applicationDbContext.ContactDetails.Remove(contact);
            var result = await _applicationDbContext.SaveChangesAsync();
            if (result > 0)
            {
                response.StatusCode = HttpStatusCode.OK;
            }
            return response;
        }
    }
}

The controller needs to be injected with the ApplicationDbContext class which is used for the database operation.

_applicationDbContext.ContactDetails.ToListAsync() 
// The query returns all the rows on the ContactDetails table 

_applicationDbContext.ContactDetails.Where(x => x.FirstName == firstName).ToListAsync()
// The query filters the table ContactDetails and returs list of details which matches firstName with the queried firstName value

_applicationDbContext.ContactDetails.AddAsync(contact);
//The query adds the object value as a row on the table ContactDetails


_applicationDbContext.ContactDetails.FirstOrDefault(x => x.Id == contact.Id);
// The query filters the table ContactDetails and returs details which matches id with the queried id value

Contact contact = new Contact{Id = id}; _applicationDbContext.ContactDetails.Remove(contact)
// the query removes the row which matches the id of the provided id value

The only and the main thing now left is the database migration.

Migration:

We will use the inbuilt Package Manager Console of Visual Studio 2019 for carrying out the operation.

  1. add-migration initialmigration //add-migration is the command for adding a migration and initialmigration is the migration name
  2. update-database //update-database is the command for updating the database with the migration values

Entity Framework Core For Beginners In Asp.Net Core Add Migration

Entity Framework Core For Beginners In Asp.Net Core Update Database

For the particular scenario since its a new project the update-database command will simply add the entity i.e. Contact.cs which is the part of WebApi.Shared Class Library as a table with the name ContactDetails on the database mentioned on the appsetting.json file earlier.

We have come to the end of the tutorial and our API application is complete which we can test from Postman or simply via Swagger UI since I have integrated swagger UI the application itself.

Some screenshots of the test:

Add Contact

Entity Framework Core For Beginners In Asp.Net Core Add Contact Details

Contact List

Entity Framework Core For Beginners In Asp.Net Core Get Contact Lists

Contact By First Name

Entity Framework Core For Beginners In Asp.Net Core Contact Details Search

Update Contact

Entity Framework Core For Beginners In Asp.Net Core Update Contact Details

Remove Contact

Entity Framework Core For Beginners In Asp.Net Core Remove Contact Details

If you want to try the code directly you can get the codes via my Github Repository https://github.com/rashik-tuladhar/Entity-Framework-Core-In-.Net-Core.

Do share the post if you find the blog post effective and helpful.

#SharingIsCaring 🙂

2 1 vote
Article Rating
Subscribe
Notify of
guest
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Tejal Vaijoo
Tejal Vaijoo
3 months ago

Your blogs are delightful, Please keep posting often

2
0
Would love your thoughts, please comment.x
()
x