
یادگیری سی شارپ از مفاهیم پایه تا پروژه محور: شیگرایی، کار با SQL و LINQ، ORMها (Entity Framework)، ساخت پروژه مدیریت رستوران با گزارشات حرفهای و امکانات کامل!
مشاهده بیشتر
یادگیری MVC Core از مبانی تا پیشرفته: شیگرایی، Routing، Entity Framework، امنیت، تست یونیت، Razor، Ajax، و پروژههای کاربردی! یک دوره کامل برای تسلط بر توسعه وب با ASP.NET Core. به صورت حضوری و آنلاین!
مشاهده بیشترمشخصات مقاله
آموزش MVC Core-شروع کار با Entity Framework Core 2.0 ASP.NET Core 2.0
شروع کار با Entity Framework Core 2.0 ASP.NET Core 2.0
این مقاله نشان می دهد چگونه یک برنامه Entity Framework Core 2.0 MVC Web با استفاده از Visual Studio 2017 و ASP.NET Core ایجاد کنیم و چگونه عملیات CRUD را به برنامه اضافه کنیم.
Prerequirements
برای اینکه بتوانید این مثال را از طریق دانلود یا ساخت آن از ابتدا اجرا کنید، باید ابزارهای زیر را داشته باشید:
- Visual Studio 2017 latest version
- .NET Core 2.0 or above
مراحل تکمیل این مقاله،
- 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
یک solution جدید ایجاد کنید و نام آن را BlogAspNetMvcEfCoreVs2017Solution کنید.

یک پروژه جدید ASP.NET Core web application اضافه کنید و آن را به عنوان BlogUi نامگذاری کنید.

سپس قالب Web Application (Model-View-Controller) را انتخاب کنید:

برنامه را کامپایل و اجرا کنید و صفحه اصلی را ببینید.

Add Models
- Blog
- Post
- DataContext
ما به پروژه اضافه خواهیم کرد:
- یک فولدر به نام EF
- یک کلاس Post
- یک کلاس Blog
- و یک کلاس DataContext مثل تصویر زیر.
کلاس Post را به پوشه Models اضافه کنید.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | //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; } } } <button></button> |
کلاس Blog را به پوشه Models اضافه کنید.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | //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 >(); } } <button></button> |
کلاس DataContext را به پوشه EF اضافه کنید.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | //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; } } } <button></button> |
Update Startup.cs file
ما باید سرویس DbContext خود را با یک connection string با پایگاه داده مانند زیر مقایسه کنیم. این 2 خط را به متد ConfigureServices اضافه کنید.
1 2 3 | var connection = @ "Server=(localdb)\mssqllocaldb;Database=BlogEfDB;Trusted_Connection=True;" ; services.AddDbContext< DataContext >(options => options.UseSqlServer(connection)); <button></button> |
در اینجا فایل completeStartup.cs است:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | 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?}" ); }); } } } <button></button> |
سپس ما باید فایل BlogUi.cproj را با DotNetCliToolReference به روز کنیم.
1 2 3 4 5 6 | < ItemGroup > < DotNetCliToolReference Include= "Microsoft.EntityFrameworkCore.Tools.DotNet" > < Version >2.0.0-*< /Version > < /DotNetCliToolReference > < /ItemGroup > <button></button> |
در اینجا فایل BlogUi.cproj به روز شده است.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | < 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 > <button></button> |
پروژه Compile شده و هیچ خطایی وجود ندارد.
[Package Manager console] را باز کرده و پروژه پیش فرض را BlogUi انتخاب می کنیم.
دستور add-migration initialCreate را وارد می کنیم.
بعد از اجرا شدن کامل دستور بالا دستور جدیدی update-database –verbose وارد می کنیم.
Microsoft SQL Management Studio نشان می دهد که پایگاه داده BlogEfDB ما با جداول Blogs و Posts ایجاد شده است.
یک BlogController را بر روی پوشه Controllers اضافه کنید.

BlogsController را توسط scaffolding ایجاد می کنیم:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | 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); } } } <button></button> |
بیایید پروژه را اجرا کنیم و به http: // localhost: 63139 / blog برویم.
یک مورد blog اضافه کنید.

این تست و اشکال زدایی Web API را تکمیل خواهد کرد.
Summary
در این مقاله، ما آموخته ایم که چگونه می توان برنامه Entity Framework Core 2.0 MVC Web را با استفاده از Visual Studio 2017 و ASP.NET Core ایجاد کرد. source code این پروژه را از لینک زیر می توانید دانلود کنید:
1 | https: //github.com/SmartITAz/BlogAspNetMvcEfCoreVs2017Solution<button></button> |
شما دانشجویان محترم می توانید فایل همراه این مقاله را از پایین صفحه دانلود نمایید.