简介:
本文主要介绍ASP .NET Core中使用EF Core(Entity Framework Core),其中DbContext配置及创建使用的方法。
Dbcontext代码
public class BlexzWebDb : DbContext
{
public BlexzWebDb(DbContextOptions<BlexzWebDb> options)
: base(options)
{ }
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<AssignedRole> AssignedRoles { get; set; }
}
在EF Core中,通常将一些DbContextOptions
传递给构造函数。一般来说,构造函数是这样的:
public BlexzWebDb(DbContextOptions<BlexzWebDb> 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<BlexzWebDb>(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;
}
}
了解更多分析及数据抓取可查看:
http://data.yisurvey.com:8989/
特别说明:本文旨在技术交流,请勿将涉及的技术用于非法用途,否则一切后果自负。如果您觉得我们侵犯了您的合法权益,请联系我们予以处理。