برای ایجاد یک برنامه ASP.NET Core 6 که کلاس Student را به صورت Code First در SQL Server پیاده سازی کرده و از الگوی Repository برای عملیات CRUD استفاده می کند، ابتدا باید یک پروژه جدید ایجاد کنید و پروژه وابستگیهای مورد نیاز را اضافه کنید.
- ابتدا به کمک دستور زیر یک پروژه جدید ایجاد نمایید:
dotnet new mvc --name StudentMvcApp
- سپس وارد شوید به پروژه و پکیجهای مورد نیاز را اضافه نمایید:
cd StudentMvcApp
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Design
- حالا میتوانیم کلاس Student و DbContext را به پروژه اضافه کنید. در اینجا مثالها را در مسیر
StudentMvcApp/Models قرار میدهیم.
Models/Student.cs:
public class Student
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
}
Models/AppDbContext.cs:
using Microsoft.EntityFrameworkCore;
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
public DbSet<Student> Students { get; set; }
}
- در قدم بعدی، ما کلاسهای Repository را ایجاد میکنیم.
Models/IRepository.cs:
using System.Collections.Generic;
public interface IRepository<T> where T : class
{
IEnumerable<T> GetAll();
T Get(int id);
void Add(T entity);
void Update(T entity);
void Delete(T entity);
}
Models/StudentRepository.cs:
using System.Collections.Generic;
using System.Linq;
public class StudentRepository : IRepository<Student>
{
private readonly AppDbContext _dbContext;
public StudentRepository(AppDbContext dbContext)
{
_dbContext = dbContext;
}
public IEnumerable<Student> GetAll()
{
return _dbContext.Students;
}
public Student Get(int id)
{
return _dbContext.Students.FirstOrDefault(s => s.Id == id);
}
public void Add(Student student)
{
_dbContext.Students.Add(student);
_dbContext.SaveChanges();
}
public void Update(Student student)
{
_dbContext.Students.Update(student);
_dbContext.SaveChanges();
}
public void Delete(Student student)
{
_dbContext.Students.Remove(student);
_dbContext.SaveChanges();
}
}
- در قدم بعدی، به appsettings.json بروید و رشته اتصال به SQL Server را اضافه کنید:
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=StudentDb;Trusted_Connection=True;"
},
...
}
- به Startup.cs بروید و تنظیمات DbContext و Repository را اضافه کنید:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddScoped<IRepository<Student>, StudentRepository>();
services.AddControllersWithViews();
}
- در نهایت، کنترل کننده خود را ایجاد کنید و عملیات CRUD را پیاده سازی کنید. برای این کار فایل
Controllers/StudentController.cs را ایجاد کرده و کدهای زیر را در آن قرار دهید:
using Microsoft.AspNetCore.Mvc;
using System.Linq;
public class StudentController : Controller
{
private readonly IRepository<Student> _repository;
public StudentController(IRepository<Student> repository)
{
_repository = repository;
}
public IActionResult Index()
{
return View(_repository.GetAll().ToList());
}
public IActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Student student)
{
if (ModelState.IsValid)
{
_repository.Add(student);
return RedirectToAction(nameof(Index));
}
return View(student);
}
public IActionResult Edit(int id)
{
var student = _repository.Get(id);
if (student == null)
{
return NotFound();
}
return View(student);
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Edit(int id, Student student)
{
if (id != student.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
_repository.Update(student);
return RedirectToAction(nameof(Index));