範例講解

本範例會簡單示範 EntityFramework 的寫法。

範例下載

從資料庫建 DB Model 的指令(以北風資料庫為範例): dotnet ef dbcontext scaffold "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Northwind;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" Microsoft.EntityFrameworkCore.SqlServer --output-dir Models/DBModels

一開始先在 Startup.cs 設定 DbContext:

public void ConfigureServices(IServiceCollection services)
{
    //DB setup
    services.AddEntityFrameworkSqlServer();
    services.AddDbContext<NorthwindContext>(options =>
    {
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
    });
    _ = services.AddScoped<DbContext, NorthwindContext>();
    services.AddScoped<IEmployeesRepository, EmployeesRepository>();
    services.AddScoped<ICustomersRepository, CustomersRepository>();

    //services setup
    services.AddScoped<IEmployeesService, EmployeesService>();
    services.AddScoped<ICustomersService, CustomersService>();

    services.AddControllersWithViews();
}

在 Controller 上的使用:

[HttpGet]
public IActionResult TestCustomers()
{
    var result = _customersService.GetAll();
    return new JsonResult(result);
}

[HttpGet]
public IActionResult TestCustomer()
{
    Customers customer = _customersService.GetCustomerByID("ANATR");
    return new JsonResult(customer);
}

參考資料