1. 程式人生 > 其它 >.net Core 呼叫EF Core 爬坑

.net Core 呼叫EF Core 爬坑

.net Core 中呼叫 EF Core專案

首先得建一個類庫供.net Core 的主專案引用;其次,在.net Core 中做注入;最後,在頁面中呼叫

1、類庫專案中的操作

   1.新建類庫專案

   2.新建Entity Class,表名為:Products Entity Class Name :Product

   3.Create DBContext File:

   1.Create Construction 建構函式 DBContext File name:MyDBContext 繼承:DBContext 建構函式::base(opt)實質是為了.net Core 注入傳參 public MyDBContext(DbContextOptions<MyDBContext> opt):base(opt){}

2.Add DbContext 屬性 注意:屬性名稱與表明一致 public DbSet<Products> Products { get; set; }

public class MyDBContext:DbContext
{
    public MyDBContext(DbContextOptions<MyDBContext> opt) :base(opt)
    { 
    }
​
    public DbSet<Product> Products { get; set; }
    ...
}

  

2、.netCore 中引用 Startup.cs中ConfigureServices 注入EF Core服務

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<Sport.Entity.SportStoreDBContext>(opt =>
    opt.UseSqlServer(Configuration.GetConnectionString("SportDB"))//appsettings.json ConnectionStrings.SportDB
    ) ; 
    ...
}

  

appsettings.json 中配置ConnectionStrings 節點值

{
     "Logging": {
         "LogLevel": {
         "Default": "Information",
         "Microsoft": "Warning",
         "Microsoft.Hosting.Lifetime": "Information"
         }
     },
     "AllowedHosts": "*",
     "ConnectionStrings": {
         "SportDB": "Server=(localdb)\\ProjectsV13;database=MyPracticeDB;Trusted_Connection=True;MultipleActiveResultSets=true"
     }
}

3 頁面中呼叫,net Core 將EF服務,以建構函式的方式提供呼叫

private readonly SportStoreDBContext _sportContext;

public HomeController(SportStoreDBContext sportContext)
{
_sportContext = sportContext;
}

//呼叫

public ActionResult List()
{

var list = _sportContext.Product.ToList();

}