开发手册 欢迎您!
软件开发者资料库

EF Core(Entity Framework Core)中实例化创建DatabaseContext方法及代码

本文主要介绍ASP .NET Core中使用EF Core(Entity Framework Core),其中DbContext配置及创建使用的方法。

Dbcontext代码

public class BlexzWebDb : DbContext{    public BlexzWebDb(DbContextOptions options)       : base(options)    { }    public DbSet Users { get; set; }    public DbSet Roles { get; set; }    public DbSet AssignedRoles { get; set; }}

在EF Core中,通常将一些DbContextOptions传递给构造函数。一般来说,构造函数是这样的:

public BlexzWebDb(DbContextOptions options) : base(options)

如你所见,没有有效的重载形式的无参数构造函数:

下面这样是不行的:

using (var db = new BlexzWebDb())

在Startup.cs中ConfigureServices()方法配置

ConfigureServices()方法中实现注册DbContext,具体代码如下:

public void ConfigureServices(IServiceCollection services){    //some mvc     services.AddMvc();    //hey, options!    services.AddDbContext(options =>            options.UseSqlServer(Configuration.GetConnectionString("BlexzWebConnection")));
//...省略不相关的代码
}

在Controller中获取DbContext对象的代码

public class SomeController : Controller{    private readonly BlexzWebDb _db;    //the framework handles this    public SomeController(BlexzWebDb db)    {        _db = db;    }}