zoukankan      html  css  js  c++  java
  • 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;
            }
         }
  • 相关阅读:
    HTTP/1.1 Status Code Definitions
    宽带到底“宽不宽”
    tmux的简介及使用
    Simple Gesture – Fling
    使用postfix搭建匿名smtp服务器
    dos2unix和unix2dos命令使用 [〓 脚本功略 〓]
    Android Coding: Gestures Builder: create your gestures library
    Android Gesture 手势识别使用实例 Android mobile ITeye论坛
    使用socat进行端口转发
    notepad++在编辑python文件时以4个空格代替TAB
  • 原文地址:https://www.cnblogs.com/Adoni/p/12270153.html
Copyright © 2011-2022 走看看