Getting Started With Entity Framework Core 2.0 ASP.NET Core 2.0

This article shows how to create Entity Framework Core 2.0 MVC Web application using Visual Studio 2017 Asp.Net Core and how to create CRUD operations.

This article shows how to create Entity Framework Core 2.0 MVC Web application using Visual Studio 2017, ASP.NET Core, and how to create CRUD operations. 

Prerequirements

To be able to run the example from the download or build it from scratch, you need to have the following tools:

  • Visual Studio 2017 latest version
  • .NET Core 2.0 or above

Steps to complete this article,

  • Create a solution with an MVC Core 2.0 project
  • Add Models(Blog, Post)
  • Add DbContect
  • Update StartUp
  • update project file
  • add migration -[Package Manager console]
  • update-database -verbose

Create a new solution and name it as BlogAspNetMvcEfCoreVs2017Solution.

ASP.NET Core 2.0

Add a new ASP.NET Core web application project and name it as BlogUi.

ASP.NET Core 2.0

Next, select "Web Application (Model-View-Controller)" template.

ASP.NET Core 2.0

Compile and run the application and we’ll see the home page.

ASP.NET Core 2.0

Add Models

  • Blog
  • Post
  • DataContext

We will add into the project

  • A folder named EF
  • A Post class
  • A Blog class
  • And, a DataContext class like below screenshot.

    ASP.NET Core 2.0

Add a Post class into the Models folder. 

  1. //Copyright 2017 (c) SmartIT. All rights reserved.  
  2. //By John Kocer  
  3. // This file is for Swagger test, this application does not use this file  
  4.   
  5. namespace BlogUi.Models  
  6. {  
  7.   public class Post  
  8.   {  
  9.     public int Id { get; set; }  
  10.     public int BlogId { get; set; }  
  11.     public string Title { get; set; }  
  12.     public string Body { get; set; }  
  13.     public Blog Blog { get; set; }  
  14.   }  
  15. }  

Add a Blog class into the Models folder.

  1. //Copyright 2017 (c) SmartIT. All rights reserved.  
  2. //By John Kocer  
  3. // This file is for Swagger test, this application does not use this file  
  4. using System.Collections.Generic;  
  5.   
  6. namespace BlogUi.Models  
  7. {  
  8.   public class Blog  
  9.   {  
  10.     public int Id { get; set; }  
  11.     public string Title { get; set; }  
  12.     public string Description { get; set; }  
  13.     public ICollection<Post> Posts { get; set; } = new List<Post>();  
  14.   }  
  15. }  
Add a DataContext class into the EF folder.
  1. //Copyright 2017 (c) SmartIT. All rights reserved.  
  2. //By John Kocer  
  3. // This file is for Swagger test, this application does not use this file  
  4. using BlogUi.Models;  
  5. using Microsoft.EntityFrameworkCore;  
  6.   
  7. namespace BlogUi.Ef  
  8. {  
  9.   public class DataContext : DbContext  
  10.   {  
  11.     public DataContext(DbContextOptions<DataContext> options) : base(options){}  
  12.   
  13.     public DbSet<Blog> Blog { get; set; }  
  14.     public DbSet<Post> Post { get; set; }  
  15.   }  
  16. }  
Update Startup.cs file

We need to configure our DbContext service with a database connection string like below. Add these 2 lines into ConfigureServices method.

  1. var connection = @"Server=(localdb)\mssqllocaldb;Database=BlogEfDB;Trusted_Connection=True;";  
  2.       services.AddDbContext<DataContext>(options => options.UseSqlServer(connection));  
Here is the completeStartup.cs file.
  1. using Microsoft.AspNetCore.Builder;  
  2. using Microsoft.AspNetCore.Hosting;  
  3. using Microsoft.Extensions.Configuration;  
  4. using Microsoft.Extensions.DependencyInjection;  
  5. using Microsoft.EntityFrameworkCore;  
  6. using BlogUi.Ef;  
  7.   
  8. namespace BlogUi  
  9. {  
  10.   public class Startup  
  11.   {  
  12.     public Startup(IConfiguration configuration)  
  13.     {  
  14.       Configuration = configuration;  
  15.     }  
  16.   
  17.     public IConfiguration Configuration { get; }  
  18.   
  19.     // This method gets called by the runtime. Use this method to add services to the container.  
  20.     public void ConfigureServices(IServiceCollection services)  
  21.     {  
  22.       var connection = @"Server=(localdb)\mssqllocaldb;Database=BlogEfDB;Trusted_Connection=True;";  
  23.       services.AddDbContext<DataContext>(options => options.UseSqlServer(connection));  
  24.       services.AddMvc();  
  25.     }  
  26.   
  27.     // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  28.     public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
  29.     {  
  30.       if (env.IsDevelopment())  
  31.       {  
  32.         app.UseDeveloperExceptionPage();  
  33.         app.UseBrowserLink();  
  34.       }  
  35.       else  
  36.       {  
  37.         app.UseExceptionHandler("/Home/Error");  
  38.       }  
  39.   
  40.       app.UseStaticFiles();  
  41.   
  42.       app.UseMvc(routes =>  
  43.       {  
  44.         routes.MapRoute(  
  45.                   name: "default",  
  46.                   template: "{controller=Home}/{action=Index}/{id?}");  
  47.       });  
  48.     }  
  49.   }  
  50. }  
Then we need to update BlogUi.cproj file with DotNetCliToolReference.
  1. <ItemGroup>  
  2.     <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet">  
  3.       <Version>2.0.0-*</Version>  
  4.     </DotNetCliToolReference>  
  5.   </ItemGroup>  

Here is the updated BlogUi.cproj file.

  1. <Project Sdk="Microsoft.NET.Sdk.Web">  
  2.   
  3.   <PropertyGroup>  
  4.     <TargetFramework>netcoreapp2.0</TargetFramework>  
  5.   </PropertyGroup>  
  6.   
  7.   <ItemGroup>  
  8.     <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />  
  9.   </ItemGroup>  
  10.   
  11.   <ItemGroup>  
  12.     <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />  
  13.   </ItemGroup>  
  14.   
  15.  <ItemGroup>  
  16.     <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet">  
  17.       <Version>2.0.0-*</Version>  
  18.     </DotNetCliToolReference>  
  19.   </ItemGroup>  
  20. </Project>  
Compile the project. It is compiled without any error. 

[Package Manager console] on the Default project is BlogUi selected. 

add-migration initialCreate 

[Package Manager console]

update-database -verbose

Microsoft SQL Management Studio shows that our BlogEfDB database is created with Blogs and Posts tables.

ASP.NET Core 2.0

Add a BlogController onto Controllers folder.

ASP.NET Core 2.0

ASP.NET Core 2.0

ASP.NET Core 2.0

ASP.NET Core 2.0

ASP.NET Core 2.0

BlogsController created by scaffolding -

  1. using System.Linq;  
  2. using System.Threading.Tasks;  
  3. using Microsoft.AspNetCore.Mvc;  
  4. using Microsoft.EntityFrameworkCore;  
  5. using BlogUi.Ef;  
  6. using BlogUi.Models;  
  7.   
  8. namespace BlogUi.Controllers  
  9. {  
  10.   public class BlogsController : Controller  
  11.     {  
  12.         private readonly DataContext _context;  
  13.   
  14.         public BlogsController(DataContext context)  
  15.         {  
  16.             _context = context;  
  17.         }  
  18.   
  19.         // GET: Blogs  
  20.         public async Task<IActionResult> Index()  
  21.         {  
  22.             return View(await _context.Blog.ToListAsync());  
  23.         }  
  24.   
  25.         // GET: Blogs/Details/5  
  26.         public async Task<IActionResult> Details(int? id)  
  27.         {  
  28.             if (id == null)  
  29.             {  
  30.                 return NotFound();  
  31.             }  
  32.   
  33.             var blog = await _context.Blog  
  34.                 .SingleOrDefaultAsync(m => m.Id == id);  
  35.             if (blog == null)  
  36.             {  
  37.                 return NotFound();  
  38.             }  
  39.   
  40.             return View(blog);  
  41.         }  
  42.   
  43.         // GET: Blogs/Create  
  44.         public IActionResult Create()  
  45.         {  
  46.             return View();  
  47.         }  
  48.   
  49.         // POST: Blogs/Create  
  50.         // To protect from overposting attacks, please enable the specific properties you want to bind to, for   
  51.         // more details see http://go.microsoft.com/fwlink/?LinkId=317598.  
  52.         [HttpPost]  
  53.         [ValidateAntiForgeryToken]  
  54.         public async Task<IActionResult> Create([Bind("Id,Title,Description")] Blog blog)  
  55.         {  
  56.             if (ModelState.IsValid)  
  57.             {  
  58.                 _context.Add(blog);  
  59.                 await _context.SaveChangesAsync();  
  60.                 return RedirectToAction(nameof(Index));  
  61.             }  
  62.             return View(blog);  
  63.         }  
  64.   
  65.         // GET: Blogs/Edit/5  
  66.         public async Task<IActionResult> Edit(int? id)  
  67.         {  
  68.             if (id == null)  
  69.             {  
  70.                 return NotFound();  
  71.             }  
  72.   
  73.             var blog = await _context.Blog.SingleOrDefaultAsync(m => m.Id == id);  
  74.             if (blog == null)  
  75.             {  
  76.                 return NotFound();  
  77.             }  
  78.             return View(blog);  
  79.         }  
  80.   
  81.         // POST: Blogs/Edit/5  
  82.         // To protect from overposting attacks, please enable the specific properties you want to bind to, for   
  83.         // more details see http://go.microsoft.com/fwlink/?LinkId=317598.  
  84.         [HttpPost]  
  85.         [ValidateAntiForgeryToken]  
  86.         public async Task<IActionResult> Edit(int id, [Bind("Id,Title,Description")] Blog blog)  
  87.         {  
  88.             if (id != blog.Id)  
  89.             {  
  90.                 return NotFound();  
  91.             }  
  92.   
  93.             if (ModelState.IsValid)  
  94.             {  
  95.                 try  
  96.                 {  
  97.                     _context.Update(blog);  
  98.                     await _context.SaveChangesAsync();  
  99.                 }  
  100.                 catch (DbUpdateConcurrencyException)  
  101.                 {  
  102.                     if (!BlogExists(blog.Id))  
  103.                     {  
  104.                         return NotFound();  
  105.                     }  
  106.                     else  
  107.                     {  
  108.                         throw;  
  109.                     }  
  110.                 }  
  111.                 return RedirectToAction(nameof(Index));  
  112.             }  
  113.             return View(blog);  
  114.         }  
  115.   
  116.         // GET: Blogs/Delete/5  
  117.         public async Task<IActionResult> Delete(int? id)  
  118.         {  
  119.             if (id == null)  
  120.             {  
  121.                 return NotFound();  
  122.             }  
  123.   
  124.             var blog = await _context.Blog  
  125.                 .SingleOrDefaultAsync(m => m.Id == id);  
  126.             if (blog == null)  
  127.             {  
  128.                 return NotFound();  
  129.             }  
  130.   
  131.             return View(blog);  
  132.         }  
  133.   
  134.         // POST: Blogs/Delete/5  
  135.         [HttpPost, ActionName("Delete")]  
  136.         [ValidateAntiForgeryToken]  
  137.         public async Task<IActionResult> DeleteConfirmed(int id)  
  138.         {  
  139.             var blog = await _context.Blog.SingleOrDefaultAsync(m => m.Id == id);  
  140.             _context.Blog.Remove(blog);  
  141.             await _context.SaveChangesAsync();  
  142.             return RedirectToAction(nameof(Index));  
  143.         }  
  144.   
  145.         private bool BlogExists(int id)  
  146.         {  
  147.             return _context.Blog.Any(e => e.Id == id);  
  148.         }  
  149.     }  
  150. }  
Let's run the project and go to the http://localhost:63139/blogs.

Add a blog item.

ASP.NET Core 2.0

This will complete the testing and debuging of the Web API.

Summary

In this article, we have learned how to create Entity Framework Core 2.0 MVC Web application using Visual Studio 2017 and ASP.NET Core.

Download the source code from GitHub.

Thank you for reading this article. You may be interested in reading below Training articles too.