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.
Add a new ASP.NET Core web application project and name it as BlogUi.
Next, select "Web Application (Model-View-Controller)" template.
Compile and run the application and we’ll see the home page.
Add Models
Add a new ASP.NET Core web application project and name it as BlogUi.
Next, select "Web Application (Model-View-Controller)" template.
Compile and run the application and we’ll see the home page.
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.
Add a Post class into the Models folder.
- //Copyright 2017 (c) SmartIT. All rights reserved.
- //By John Kocer
- // This file is for Swagger test, this application does not use this file
- namespace BlogUi.Models
- {
- public class Post
- {
- public int Id { get; set; }
- public int BlogId { get; set; }
- public string Title { get; set; }
- public string Body { get; set; }
- public Blog Blog { get; set; }
- }
- }
Add a Blog class into the Models folder.
- //Copyright 2017 (c) SmartIT. All rights reserved.
- //By John Kocer
- // This file is for Swagger test, this application does not use this file
- using System.Collections.Generic;
- namespace BlogUi.Models
- {
- public class Blog
- {
- public int Id { get; set; }
- public string Title { get; set; }
- public string Description { get; set; }
- public ICollection<Post> Posts { get; set; } = new List<Post>();
- }
- }
- //Copyright 2017 (c) SmartIT. All rights reserved.
- //By John Kocer
- // This file is for Swagger test, this application does not use this file
- using BlogUi.Models;
- using Microsoft.EntityFrameworkCore;
- namespace BlogUi.Ef
- {
- public class DataContext : DbContext
- {
- public DataContext(DbContextOptions<DataContext> options) : base(options){}
- public DbSet<Blog> Blog { get; set; }
- public DbSet<Post> Post { get; set; }
- }
- }
We need to configure our DbContext service with a database connection string like below. Add these 2 lines into ConfigureServices method.
- var connection = @"Server=(localdb)\mssqllocaldb;Database=BlogEfDB;Trusted_Connection=True;";
- services.AddDbContext<DataContext>(options => options.UseSqlServer(connection));
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.EntityFrameworkCore;
- using BlogUi.Ef;
- namespace BlogUi
- {
- 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)
- {
- var connection = @"Server=(localdb)\mssqllocaldb;Database=BlogEfDB;Trusted_Connection=True;";
- services.AddDbContext<DataContext>(options => options.UseSqlServer(connection));
- services.AddMvc();
- }
- // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
- public void Configure(IApplicationBuilder app, IHostingEnvironment env)
- {
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- app.UseBrowserLink();
- }
- else
- {
- app.UseExceptionHandler("/Home/Error");
- }
- app.UseStaticFiles();
- app.UseMvc(routes =>
- {
- routes.MapRoute(
- name: "default",
- template: "{controller=Home}/{action=Index}/{id?}");
- });
- }
- }
- }
- <ItemGroup>
- <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet">
- <Version>2.0.0-*</Version>
- </DotNetCliToolReference>
- </ItemGroup>
Here is the updated BlogUi.cproj file.
- <Project Sdk="Microsoft.NET.Sdk.Web">
- <PropertyGroup>
- <TargetFramework>netcoreapp2.0</TargetFramework>
- </PropertyGroup>
- <ItemGroup>
- <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
- </ItemGroup>
- <ItemGroup>
- <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
- </ItemGroup>
- <ItemGroup>
- <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet">
- <Version>2.0.0-*</Version>
- </DotNetCliToolReference>
- </ItemGroup>
- </Project>
[Package Manager console] on the Default project is BlogUi selected.
add-migration initialCreate
add-migration initialCreate
[Package Manager console]
update-database -verbose
update-database -verbose
Microsoft SQL Management Studio shows that our BlogEfDB database is created with Blogs and Posts tables.
Add a BlogController onto Controllers folder.
BlogsController created by scaffolding -
- using System.Linq;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.EntityFrameworkCore;
- using BlogUi.Ef;
- using BlogUi.Models;
- namespace BlogUi.Controllers
- {
- public class BlogsController : Controller
- {
- private readonly DataContext _context;
- public BlogsController(DataContext context)
- {
- _context = context;
- }
- // GET: Blogs
- public async Task<IActionResult> Index()
- {
- return View(await _context.Blog.ToListAsync());
- }
- // GET: Blogs/Details/5
- public async Task<IActionResult> Details(int? id)
- {
- if (id == null)
- {
- return NotFound();
- }
- var blog = await _context.Blog
- .SingleOrDefaultAsync(m => m.Id == id);
- if (blog == null)
- {
- return NotFound();
- }
- return View(blog);
- }
- // GET: Blogs/Create
- public IActionResult Create()
- {
- return View();
- }
- // POST: Blogs/Create
- // To protect from overposting attacks, please enable the specific properties you want to bind to, for
- // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
- [HttpPost]
- [ValidateAntiForgeryToken]
- public async Task<IActionResult> Create([Bind("Id,Title,Description")] Blog blog)
- {
- if (ModelState.IsValid)
- {
- _context.Add(blog);
- await _context.SaveChangesAsync();
- return RedirectToAction(nameof(Index));
- }
- return View(blog);
- }
- // GET: Blogs/Edit/5
- public async Task<IActionResult> Edit(int? id)
- {
- if (id == null)
- {
- return NotFound();
- }
- var blog = await _context.Blog.SingleOrDefaultAsync(m => m.Id == id);
- if (blog == null)
- {
- return NotFound();
- }
- return View(blog);
- }
- // POST: Blogs/Edit/5
- // To protect from overposting attacks, please enable the specific properties you want to bind to, for
- // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
- [HttpPost]
- [ValidateAntiForgeryToken]
- public async Task<IActionResult> Edit(int id, [Bind("Id,Title,Description")] Blog blog)
- {
- if (id != blog.Id)
- {
- return NotFound();
- }
- if (ModelState.IsValid)
- {
- try
- {
- _context.Update(blog);
- await _context.SaveChangesAsync();
- }
- catch (DbUpdateConcurrencyException)
- {
- if (!BlogExists(blog.Id))
- {
- return NotFound();
- }
- else
- {
- throw;
- }
- }
- return RedirectToAction(nameof(Index));
- }
- return View(blog);
- }
- // GET: Blogs/Delete/5
- public async Task<IActionResult> Delete(int? id)
- {
- if (id == null)
- {
- return NotFound();
- }
- var blog = await _context.Blog
- .SingleOrDefaultAsync(m => m.Id == id);
- if (blog == null)
- {
- return NotFound();
- }
- return View(blog);
- }
- // POST: Blogs/Delete/5
- [HttpPost, ActionName("Delete")]
- [ValidateAntiForgeryToken]
- public async Task<IActionResult> DeleteConfirmed(int id)
- {
- var blog = await _context.Blog.SingleOrDefaultAsync(m => m.Id == id);
- _context.Blog.Remove(blog);
- await _context.SaveChangesAsync();
- return RedirectToAction(nameof(Index));
- }
- private bool BlogExists(int id)
- {
- return _context.Blog.Any(e => e.Id == id);
- }
- }
- }
Add a blog item.
This will complete the testing and debuging of the Web API.
Summary
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.
No comments:
Post a Comment