码迷,mamicode.com
首页 > 其他好文 > 详细

EF Core 入门

时间:2019-03-01 17:08:24      阅读:1308      评论:0      收藏:0      [点我收藏+]

标签:soft   style   生成   logging   alt   data-   config   net   getc   

官方文档地址

 https://docs.microsoft.com/zh-cn/aspnet/?view=aspnetcore-2.2#pivot=core

 

技术图片

 

EF Core 使用

1. 创建数据库上下文和数据实体   

从Sql Server 数据库读取连接和实体,打开Nuget 包管理控制台,输入

Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

成功后会在项目中自动生成实体模型Model和数据库上下文DBContext

修改上下文实体,删除 OnConfiguring 和 OnModelCreating 方法

这里手动添加数据库上下文和数据库实体也可以 

技术图片

 

2.添加连接字符串

在appsetting.json 添加Sql Server 连接字符串

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "ConnectionStrings": {
    "LocalDB": "Data Source=db;Initial Catalog=LocalDB;User ID=spring;Password=Mm2717965346"
  },
  "AllowedHosts": "*"
}

 

3.通过依赖关系注入注册上下文 

在 Startup.cs 中注册并配置上下文

 public void ConfigureServices(IServiceCollection services)
        { 

            // 注册上下文
            services.AddDbContext<LocalDBContext>(options =>
              options.UseSqlServer(Configuration.GetConnectionString("LocalDB"))
             );


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
             
           
        }

 

4. 在程序中使用数据库上下文

这里在控制器里面示范,在控制器构造函数内初始化 上下文

 [Route("api/[controller]/[action]")]
    [ApiController]
    public class HomeController : ControllerBase
    {
        public LocalDBContext DB { get; set; }

        public HomeController(LocalDBContext db)
        {
            DB = db;
        }

然后就可以使用 DB 上下文去操作数据库, DB.Students.ToList() , DB.Add() , DB.SaveChanges()....

 

EF Core 入门

标签:soft   style   生成   logging   alt   data-   config   net   getc   

原文地址:https://www.cnblogs.com/myshowtime/p/10457396.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!