.NET Core 获取数据库上下文实例的方法和配置连接字符串

内容纲要

.NET Core 获取数据库上下文实例的方法和配置连接字符串

[TOC]

假设数据库就两个表:User、Blogs,

模型类如下

    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Number { get; set; }
        public string Email { get; set; }
    }

    public class Blogs
    {
        public int Id { get; set; }
        public string BolgName { get; set; }
        public string Url { get; set; }
    }

数据库上下文大致这样

    public class DataContext : DbContext
    {
        public DataContext()
        {
        }

        public DataContext(DbContextOptions<DataContext> options) : base(options)
        {
        }

        public DbSet<User> Users { get; set; }
        public DbSet<Blog> Blogs { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }

        /*
         * 其他实现
         */
    }

ASP.NET Core 注入

ASP.NET Core 的数据库注入是最为简单方便的了,在 ConfigureServices 配置即可。

            services.AddDbContext<DataContext>(options=>options.UseSqlite("filename=Database.db"));

然后在控制器等地方使用,不需要什么多余代码。

    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private readonly DataContext _context;

        public WeatherForecastController(DataContext context)
        {
            _context = context;
        }
     }

.NET Core 注入

需要安装一个 Nuget 包

Microsoft.Extensions.DependencyInjection

创建一个类 ContextService,用来配置注入和获取上下文。

    public class ContextService
    {
        /// <summary>
        /// 配置各种服务
        /// </summary>
        /// <returns></returns>
        public static IServiceProvider ServiceProvider()
        {
            IServiceCollection services = new ServiceCollection();

            services.AddDbContext<DataContext>(options => options.UseSqlite("filename=Database.db"));
            var serviceProvider = services.BuildServiceProvider();
            return serviceProvider;
        }

        /// <summary>
        /// 获取上下文
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static DataContext GetContext(IServiceProvider services)
        {
            var sqliteContext = services.GetService<DataContext>();
            return sqliteContext;
        }

        /// <summary>
        /// 获取上下文
        /// </summary>
        public static DataContext GetContext()
        {
            var services = ServiceProvider();
            var sqliteContext = services.GetService<DataContext>();
            return sqliteContext;
        }
    }

需要使用时可以这样获取上下文

            var context = ContextService.GetContext();
            var list = context.Users.ToList();

无签名上下文 OnConfigure 配置

上面两个示例中,连接字符串都是使用 Action<DbContextOptionsBuilder> optionsAction 来配置的。

options => options.UseSqlite("filename=Database.db")

我们可以直接在上下文的 OnConfigure 方法里,配置默认使用的连接字符串。

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {

#if DEBUG
            optionsBuilder.UseSqlite("filename=Database.db");
#endif
        }

但是,极其不建议这样做,一般可能调试环境或为了方便在里面这样做。

这种情况是上下文存在一个无签名构造函数时,外界使用此构造函数直接实例化上下文。

            var context = new DataContext();
            var list = context.Users.ToList();

这种情况下,是直接实例化上下文,并且使用默认的连接字符串。

OnConfiguring会在无注入、也没有使用有签名构造函数时才会生效,或者描述为多种配置上下文方式中优先级最低。

有签名上下文构造函数和自己new一个上下文

上下文必须具有 DbContextOptions 或 DbContextOptions<T> 的构造函数,建议使用泛型形式。

构造函数示例:

        public DataContext(DbContextOptions<DataContext> options) : base(options)
        {
        }

具有此构造函数,则可以通过外界注入配置,例如

            services.AddDbContext<DataContext>(options=>options.UseSqlite("filename=Database.db"));

如果你不使用注入(Microsoft.Extensions.DependencyInjection)或者第三方 ioc 工具,那么无法使用上面这种形式。

不过可以自己 new,自己传递配置对象,

            var optionsBuilder = new DbContextOptionsBuilder<DataContext>();
            optionsBuilder.UseSqlite("filename=Database.db");
            DataContext context = new DataContext(optionsBuilder.Options);
            var list = context.Users.ToList();

DbContextOptions 构造器

            DatabaseContext context = new DatabaseContext(options: new DbContextOptionsBuilder<DatabaseContext>().UseSqlite("H:/临时/database/Database.db").Options);

DbContextOptionsBuilder 是一个 DbContextOptions 构造器,用于在多种情况下自定义构造 DbContextOptions ,在上面的多个例子中,可以使用此构造器更加方便地构造上下文。

工良比较菜。。。上面有很多原理没有弄懂,大神看到指定一下我呗~

点赞
  1. cheap levitra说道:

    I intended to create you a little note just to give thanks as before for all the exceptional guidelines you've discussed at this time. It has been certainly incredibly generous of people like you to allow extensively all that a lot of folks could have distributed as an e-book in order to make some bucks for their own end, chiefly considering the fact that you could have done it if you considered necessary. The creative ideas additionally acted as the easy way to be certain that most people have a similar dream just like mine to find out a little more in regard to this condition. I'm certain there are lots of more enjoyable moments ahead for individuals that examine your blog.

发表评论

邮箱地址不会被公开。 必填项已用*标注

You must enable javascript to see captcha here!