2.EF Core添加数据库配置的几种方式
一、OnConfiguring:重写OnConfiguring方法添加配置信息
public class BloggingContext: DbContext { /// <summary> /// 配置数据连接信息 /// </summary> /// <param name="optionsBuilder"></param> protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseMySql("数据库连接字符串"); base.OnConfiguring(optionsBuilder); } }
二、构造函数参数方式配置
a.生成DbContextOptions
b.传入构造函数参数
var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>(); optionsBuilder.UseMySql("数据库连接字符串"); using (BloggingContext db=new BloggingContext(optionsBuilder.Options)) { return db.Blogs; }
三、容器添加方式
1、添加操作数据库上下文的构造函数
public class BloggingContext : DbContext { /// <summary> /// 容器初始化时传入options /// </summary> /// <param name="options"></param> public BloggingContext(DbContextOptions<BloggingContext> options): base(options) { } public virtual DbSet<Blog> Blogs { get; set; } public virtual DbSet<Post> Posts { get; set; } }
2、在Startup.ConfigureServices方法中添加服务依赖,这里有两种添加方式
services.AddDbContextPool<BloggingContext>(options => options.UseMySql("数据库连接字符串")); //会集成.net core 日志机制,微软推荐使用连接池的方式 services.AddDbContext<BloggingContext>(options=>options.UseMySql("数据库连接字符串"));
3、 获取方式
a.服务方式获取
using (var context = HttpContext.RequestServices.GetService<BloggingContext>()) { // do stuff }
b.控制器方式传入,参数加上[FromServices]
public IActionResult Index([FromServices]BloggingContext context) {return Content(“”); }
c.构造函数传入
public class HomeController : Controller { private readonly BloggingContext _context; public HomeController(BloggingContext context) { _context = context; } }