Entity Framework Core Sql Server for SEO

1. Add Package

Mở terminal, truy cập vào thư mục WebApp và cài đặt thư viện EntityFramworkCore với lệnh chi tiết như sau:

dotnet add package Microsoft.EntityFrameworkCore.SqlServer

2. Create Model

2.2 Create class Category

Trong thư mục Models tạo file Category.cs với nội dung sau


namespace WebApp.Models;
[Table("Category")]
public class Category{
    [Column("CategoryId")]
    public short Id { get; set; }
    [Column("CategoryName")]
    public string Name { get; set; } = null!;
}

2.2 Create TrekBikesContext

Trong thư mục Models tạo file TrekBikesContext.cs kết thừa từ class DbContext với nội dung chi tiết như sau:


namespace WebApp.Models;
public class TrekBikesContext : DbContext{
    public TrekBikesContext(DbContextOptions options):base(options) { }
    public DbSet<Category> Categories { get; set; }
}

2.3 Create BaseRepository

Trong thư mục Models tạo lớp trừu tượng dùng chung cho tất tả các lớp Repository đặt tên là BaseRepository.cs nội dung như sau:


namespace WebApp.Models;
public abstract class BaseRepository {
    protected TrekBikesContext context;
    public BaseRepository(TrekBikesContext context){
        this.context = context;
    }
}

2.4 Create CategoryRepository

Trong thư mục Models tạo tiếp class CategoryRepository, class này kế thừa từ BaseRepository và nội dung như sau


namespace WebApp.Models;
public class CategoryRepository : BaseRepository{
    public CategoryRepository(TrekBikesContext context) : base(context){
    }
    public IEnumerable<Category> GetCategories(){
        return context.Categories.ToList();
    }
}

3. Create Controller

Tạo class CategoryController trong thư mục Controllers kế thừa từ class Controller và nhập nội dung như sau:


namespace WebApp.Controllers;
public class CategoryController : Controller{
    CategoryRepository categoryRepository;
    public CategoryController(CategoryRepository categoryRepository){
        this.categoryRepository = categoryRepository;
    }
    public IActionResult Index(){
        return View(categoryRepository.GetCategories());
    } 
}

4. Create View

4.1 Create ViewImports

Trong thư mục Views tạo file _ViewImports.cshtml để khải báo sử dụng 2 thư viện WebApp.Models và khai báo sử dụng TagHelper với nội dung sau:


@using WebApp.Models
@addTagHelper *,Microsoft.AspNetCore.Mvc.TagHelpers

4.2 Create View CategoryController

Tạo thư mục Category trong thư mục Views tương ứng với controller CategoryController, trong thư mục này tạo file Index.cshtml để tạo view cho action tương ứng là Index cho controller CategoryController đặt tên là Index.cshtml nội dung hiển thị thông tin như sau:


@model IEnumerable<Category>
<table>
    <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Method</th>
        </tr>
    </thead>
    <tbody>
        @foreach(Category item in Model){
            <tr>
                <td>@item.Id</td>
                <td>@item.Name</td>
                <td>
                    <a href="/category/edit/@item.Id">Edit</a>
                    <a href="/category/delete/@item.Id">Delete</a>
                </td>
            </tr>
        }
    </tbody>
</table>

4. DI

Vào Program.cs khai báo DI cho 2 class TrekBikesContext và CategoryRepository với nội dung như sau:


builder.Services.AddDbContext<TrekBikesContext>(p => p.UseSqlServer(builder.Configuration.GetConnectionString("TrekBikes")));
builder.Services.AddScoped<CategoryRepository>();

5. AppSettings

Thêm vào chuỗi kết nối trong file appsetttings.json với nội dung như sau:

{
  "ConnectionStrings": {
    "TrekBikes": "Server=.;Database=TrekBikes;Trusted_Connection=true;TrustServerCertificate=true;"
  }
}

5. Run project

Mở termial và chạy project với lệnh sau:

dotnet watch run

Truy cập vào trình duyệt web: /category