当前位置: 移动技术网 > IT编程>开发语言>.net > .NET Core 获取数据库上下文实例的方法和配置连接字符串

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

2019年11月22日  | 移动技术网IT编程  | 我要评论

耽美动漫,钟鹿纯凸点,格子铺是什么

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

假设数据库就两个表: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();

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网