Create Data with Entity Framework in ASP.NET Core Web API


Create a database named LearnASPNETCoreWebAPIWithRealApps. This database have a table: Product table as below:

USE LearnASPNETMVCWithRealApps

/* Table structure for table `product` */

GO
CREATE TABLE Product (
    Id int IDENTITY(1,1) NOT NULL PRIMARY KEY,
	Name varchar(250) NULL,
	Price money NULL,
	Quantity int NULL,
	Status bit NOT NULL
)

/* Dumping data for table `product` */
GO
INSERT Product(Name, Price, Quantity, Status) VALUES('Name 1', 20.0000, 4, 1)
GO
INSERT Product(Name, Price, Quantity, Status) VALUES('Name 2', 12.0000, 8, 0)
GO
INSERT Product(Name, Price, Quantity, Status) VALUES('Name 3', 4.0000, 3, 1)
GO
INSERT Product(Name, Price, Quantity, Status) VALUES('Name 4', 17.0000, 8, 1)




On the Visual Studio, create new ASP.NET Core Web API Application project

Select Empty Template

Click Ok button to Finish

Open Startup.cs file and add new configurations as below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace LearnASPNETCoreWebAPIWithRealApps
{
    public class Startup
    {

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }
    }
}

Select Project and right click to select Add\New Item Menu

Select Web\ASP.NET in left side. Select App Settings File item and click Add button to Finish

In appsettings.json file and new configurations as below:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=.;Database=LearnASPNETCoreWebAPIWithRealApps;user id=sa;password=123456"
  }
}




Create new folder named Models. In Models folder, create new entity class as below:

Create new class named Product.cs as below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace LearnASPNETCoreWebAPIWithRealApps.Models
{
    public class Product
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public decimal Price { get; set; }

        public int Quantity { get; set; }

        public bool Status { get; set; }
    }
}

In Models folder, create new class named DataContext.cs, this file use Entity Framework to interact with the database as below:

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace LearnASPNETCoreWebAPIWithRealApps.Models
{
    public class DataContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            var builder = new ConfigurationBuilder()
                                    .SetBasePath(Directory.GetCurrentDirectory())
                                    .AddJsonFile("appsettings.json");
            var configuration = builder.Build();
            optionsBuilder.UseSqlServer(configuration["ConnectionStrings:DefaultConnection"]);
        }

        public DbSet<Product> Product { get; set; }

    }
}

Create new folder named Controllers. In this folder, create new controller named ProductController.cs, this file contains Web API as below:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using LearnASPNETCoreWebAPIWithRealApps.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace LearnASPNETCoreWebAPIWithRealApps.Controllers
{
    [Route("api/product")]
    public class ProductController : Controller
    {
        private DataContext db = new DataContext();

        [Consumes("application/json")]
        [Produces("application/json")]
        [HttpPost("create")]
        public async Task<IActionResult> Create([FromBody] Product product)
        {
            try
            {
                db.Product.Add(product);
                db.SaveChanges();
                return Ok(product);
            }
            catch
            {
                return BadRequest();
            }
        }

    }
}




Create Console App (.NET Framework) Project in Visual Studio.

Create Models folder in Console Application. In this folder, create new class named Product.cs as below:

Product Entity

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LearnASPNETCoreWebAPIWithRealApps_Client.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public int Quantity { get; set; }
        public bool Status { get; set; }
    }
}

ProductRestClientModel class contain methods call Web API. Add reference to System.Net.Http.Formatting library from Nuget Packages

using LearnASPNETCoreWebAPIWithRealApps_Client.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace LearnASPNETCoreWebAPIWithRealApps_Client
{
    public class ProductRestClientModel
    {
        private string BASE_URL = "http://localhost:18942/api/product/";

        public Task<HttpResponseMessage> Create(Product product)
        {
            try
            {
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri(BASE_URL);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                return client.PostAsJsonAsync("create", product);
            }
            catch
            {
                return null;
            }
        }

    }
}
using LearnASPNETCoreWebAPIWithRealApps_Client.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace LearnASPNETCoreWebAPIWithRealApps_Client
{
    class Program
    {
        static void Main(string[] args)
        {
            var productRestClientModel = new ProductRestClientModel();
            var product = new Product()
            {
                Name = "name 5",
                Price = 12,
                Quantity = 3,
                Status = true
            };
            var httpResponseMessage = productRestClientModel.Create(product).Result;
            var productInfo = httpResponseMessage.Content.ReadAsAsync<Product>().Result;
            var httpStatusCode = httpResponseMessage.StatusCode;
            Console.WriteLine("Status Code: " + httpStatusCode);
            bool isSuccessStatusCode = httpResponseMessage.IsSuccessStatusCode;
            Console.WriteLine("IsSuccessStatusCode: " + isSuccessStatusCode);
            Console.WriteLine("New Product Information");
            Console.WriteLine("Id: " + productInfo.Id);
            Console.WriteLine("Name: " + productInfo.Name);
            Console.WriteLine("Price: " + productInfo.Price);
            Console.WriteLine("Quantity: " + productInfo.Quantity);
            Console.WriteLine("Status: " + productInfo.Status);

            Console.ReadLine();
        }
    }
}




Status Code: OK
IsSuccessStatusCode: True
New Product Information
Id: 2021
Name: name 5
Price: 12.0
Quantity: 3
Status: True

I recommend you refer to the books below to learn more about the knowledge in this article: