Create an ASPNet Core Web Api using EF Core
Hi, In this post I’m going to share a little overview of .NET Core and Asp.NET Core. The journey of .NET Core started with the purpose of Microsoft to build a common .NET base library that provides a common baseline that all platforms. With this vision, Microsoft had released the first open-source version of .NET Core 1.0 release on 27 June 2016, along with ASP.NET Core 1.0 and Entity Framework. This ASP.NET Core is a redesigned version of ASP.NET that can run on .NET Core or .NET Framework both. The developers can use ASP.NET Core to build web apps and services, IoT apps, and mobile backends. ASP.NET Core is also available on three different platforms — Windows, OS X, and Linux. 
 
ASP.NET Core cross-platform, high-performance, open-source framework for building web and cloud applications. Through ASP.NET Core, we can develop web apps and services, IoT apps, and mobile backends by using our favorite development tools on Windows, macOS, and Linux.

Prerequisites

Getting started with Core 3.0 web API

Step 1:-  Open Visual Studio 2019 on your computer.
 
Step 2:- Now click at "Create a new Project" area in Visual Studio 2019.
 
Create core 3.0 web api
 
Step 3:-  Select "ASP.NET Core Web Application" and hit at Next Button.
 
Create asp.net core project
 
Step 4:- In the next window, fill your project details and location. Then hit at Create Button.
 
visual studio 2019
 
Step 5:- So here the Api Template Selection UI shows up. Before selection, you should have a look at two dropdowns on top. Make sure those are filled accordingly below the image. Now select the API as your project type and click Create Button.
 
 Asp.Net core api project C#
 
Step 6:- After some loading, this project loads and you can see in the solution explorer of your visual studio with proper project structure. you can build, run and test the project. 
 
AspNet core web Api sample project
 
Step 7:- If all looks good, its time to EF core in the project. EF Core does not support visual designer for the DB model and wizard to create the entity and context classes similar to EF 6, So for Adding EF Core, there are two possibilities.
       1. Database First (With existing Database)
       2. Code First (With a new Database)
EF core Database First Approach:- If you have an existing database, using the Scaffold-DbContext command, you can generate entity and context classes based on the schema of the existing database. For the same go step by step.
       1. Open Package Manager Console(From the View menu, select Other Windows Package Manager console. ) 
       2. Install below the NuGet package one by one.
               > Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 3.0.0
Install-Package Microsoft.EntityFrameworkCore.SqlServer
               
               > Install-Package Microsoft.EntityFrameworkCore.Design -Version 3.0.0

install-Package Microsoft.EntityFrameworkCore.Design
 
               > Install-Package Microsoft.EntityFrameworkCore.Tools -Version 3.0.0 

Install-Package Microsoft EntityFrameworkCore.Tools
 
      3.  Now time to generate entity and context classes, run following command in Package Manager console.
 
Scaffold-DbContext "Server=.;Database=CoreApi;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context CoreDbContext -DataAnnotations
 
EF core Scaffolding command
 
---------------OR---------------
 
 
EF core Code First Approach:- You need to create the class that derives from DbContext, aka context class. This context class typically includes DbSet properties for each entity in the model. 
 
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace CoreApiSample.Models
{
    public partial class Classes
    {
        public Classes()
        {
            Questions = new HashSet();
        }

        [Key]
        public Guid Id { get; set; }
        public DateTimeOffset Created { get; set; }
        [StringLength(255)]
        public string CreatedBy { get; set; }
        public DateTimeOffset? Modified { get; set; }
        [StringLength(255)]
        public string ModifiedBy { get; set; }
        public bool IsActive { get; set; }
        [Required]
        [StringLength(50)]
        public string Name { get; set; }
        [Required]
        [StringLength(50)]
        public string Abbrasive { get; set; }

        [InverseProperty("Class")]
        public virtual ICollection Questions { get; set; }
    }
}
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace CoreApiSample.Models
{
    public partial class Questions
    {
        [Key]
        public Guid Id { get; set; }
        public DateTimeOffset Created { get; set; }
        [StringLength(255)]
        public string CreatedBy { get; set; }
        public DateTimeOffset? Modified { get; set; }
        [StringLength(255)]
        public string ModifiedBy { get; set; }
        public bool IsActive { get; set; }
        public Guid? ClassId { get; set; }
        public Guid? SubjectId { get; set; }
        [Required]
        public string QuestionsText { get; set; }
        public string SolutionText { get; set; }
        public byte[] ImageSolution { get; set; }
        [StringLength(20)]
        public string ImageMimeType { get; set; }
        [Column("VideoSolutionURL")]
        [StringLength(500)]
        public string VideoSolutionUrl { get; set; }
        public string Tag { get; set; }
        [StringLength(50)]
        public string Writer { get; set; }
        [StringLength(50)]
        public string Book { get; set; }

        [ForeignKey(nameof(ClassId))]
        [InverseProperty(nameof(Classes.Questions))]
        public virtual Classes Class { get; set; }
        [ForeignKey(nameof(SubjectId))]
        [InverseProperty(nameof(Subjects.Questions))]
        public virtual Subjects Subject { get; set; }
    }
}
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace CoreApiSample.Models
{
    public partial class Subjects
    {
        public Subjects()
        {
            Questions = new HashSet();
        }

        [Key]
        public Guid Id { get; set; }
        public DateTimeOffset Created { get; set; }
        [StringLength(255)]
        public string CreatedBy { get; set; }
        public DateTimeOffset? Modified { get; set; }
        [StringLength(255)]
        public string ModifiedBy { get; set; }
        public bool IsActive { get; set; }
        [Required]
        [StringLength(50)]
        public string Name { get; set; }
        [Required]
        [StringLength(50)]
        public string Abbrasive { get; set; }

        [InverseProperty("Subject")]
        public virtual ICollection Questions { get; set; }
    }
}
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;

namespace CoreApiSample.Models
{
    public partial class CoreDbContext : DbContext
    {
        public CoreDbContext()
        {
        }

        public CoreDbContext(DbContextOptions options)
            : base(options)
        {
        }

        public virtual DbSet Classes { get; set; }
        public virtual DbSet Questions { get; set; }
        public virtual DbSet Subjects { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer("Server=.;Database=CoreApi;Trusted_Connection=True;");
            }
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();

                entity.Property(e => e.Abbrasive).IsUnicode(false);

                entity.Property(e => e.Name).IsUnicode(false);
            });

            modelBuilder.Entity(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();

                entity.Property(e => e.Book).IsUnicode(false);

                entity.Property(e => e.ImageMimeType).IsUnicode(false);

                entity.Property(e => e.Tag).IsUnicode(false);

                entity.Property(e => e.Writer).IsUnicode(false);

               
            });

            modelBuilder.Entity(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();

                entity.Property(e => e.Abbrasive).IsUnicode(false);

                entity.Property(e => e.Name).IsUnicode(false);
            });

            OnModelCreatingPartial(modelBuilder);
        }

        partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
    }
}

 

Generate Entity context and classes ef core

Step 8:- Now time add the Connection string at your appsettings.json. Add below lines to appsettings.json.

 

"ConnectionStrings": {
    "Database": "Server=(local);Database=CoreApi;Trusted_Connection=True;"
  },
 
Aspnet core Appsettings
 
Step 9:- Now time add the DbContext at your Startup.cs. Add below lines to Startup.cs.
 
 services.AddDbContext(op => op.UseSqlServer(Configuration.GetConnectionString("Database")));
 
 
Asp.net core webapi
 
Step 10:- If You are using Code First Approach, then you have to run the Migration commands in the Package Manager Console. For the same go step by step.
       1. Open Package Manager Console(From the View menu, select Other Windows Package Manager console. )
       2. Run below command one by one.
               > Add-Migration CreateDb

 Add migration in ef core
         
               > Update-Database

 Webapi using EF Core 3.0
 
Step 10:- Now, Your web API is ready to build and run. Waiting for what runs ityes.

Wrapping up

In this post we’ve learned how to we can create Asp.net core 3.0 web API using EF Core. In the future post, I will let you know the implementation of Swagger documentation in the same API Project. If you like this article feel free to share it with your friends.

 
;



share post :

Popular Posts

How to Create WCF service and host in Windows Service in WCF Service / Jan 13, 2017
Static constructor in CSharp(C#.Net) in C#.Net / Feb 11, 2017
Dependency properties in WPF in WPF / Oct 01, 2018
How to use tuples with more new feature in C# 7.0 in C#.Net / Jan 20, 2017
Method Overloading in C# in C#.Net / Feb 07, 2017
Interface in c# with example in C#.Net / May 14, 2017

Tag Cloud

Say Hi It’s Free!

  • Ghaziabad Uttar Pradesh India

  • avnish@ymail.com

  • (+91)-847-107-5432

Success/Error Message Goes Here

Avnish Kumar

.Net Developer

Download Resume
Drink A Coffee With Me Today