EF Core(1.DBFirst)

Microsoft.EntityFrameworkCore

Microsoft.EntityFrameworkCore.SqlServer

Microsoft.EntityFrameworkCore.Tools

Microsoft.EntityFrameworkCore.Design

Microsoft.EntityFrameworkCore.SqlServer.Design

1.Nuget包添加以上五个

2.添加完成后开始生成实体类,打开程序包控制管理台:

 Scaffold-DbContext "这里输入你的数据库连接字符串" Microsoft.EntityFrameworkCore.SqlServer -OutputDir 目录名

3.在appsettings.json文件中添加数据库连接字符串

 "ConnectionStrings": {
    "MsSqlConnection": "server=地址; user id=服务器名称; password=密码; database=数据库名; Connection Timeout=60;"
  }

4.在Startup注入数据库连接代码

public void ConfigureServices(IServiceCollection services)
        {
            //注入上下文对象(数据库)
            services.AddDbContext<ReadContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("MsSqlConnection")));
            //注入上下文对象(数据库)
            services.AddMvc();
        }

5.修改生成实体类文件夹中的xxxContext中的xxxContext方法为:

 public ReadContext(DbContextOptions options): base(options)
        {
        }

6.以上操作完成后即可开始使用

构造函数注入上下文

 public class UserController : Controller
    {
        //构造函数注入上下文
        private readonly ReadContext _context;
        public UserController(ReadContext Context)
        {
            _context = Context;
        }
        #region base

        /// <summary>
        /// 获取单个
        /// </summary>
        /// <param name="id">Id</param>
        /// <returns></returns>
        [HttpGet("GetById")]
        public JsonResult GetById(int id)
        {
            var tt = _context.Set<SystemInfo>().Where(c => c.Id == id).ToList();
       //如需使用sql,_context.Set<TxtInfo>().FromSql(sql).ToList();
return Json(tt); } }

 

转载:作者:顾振印 出处:http://www.cnblogs.com/GuZhenYin/ 

posted @ 2018-12-18 09:25  Crazydragcool  阅读(263)  评论(0编辑  收藏  举报