EF Core 是一个ORM(对象关系映射),它使 .NET 开发人员可以使用 .NET对象操作数据库,避免了像ADO.NET访问数据库的代码,开发者只需要编写对象即可。

  EF Core 支持多种数据库引擎:

    Microsoft SQL Sever

    SQLite

    Npgsql

    MySQL

    ......

1.获取EF Core

  通过NuGet获取要使用的数据库支持。比如:Microsoft SQL Sever

  打开NuGet程序包管理器控制台,输入:Install-Package Microsoft.EntityFrameworkCore.SqlServer

2.模型

  EF Core 是通过一个模型进行数据库访问的。模型由实体类和表示与数据库中的会话组成的,以及允许你查询和保存数据派生的上下文。

  既可以从现有数据库生成模型,也可以使用EF 迁移来完成从模型生成数据库,也就是Database First 和 Code First。

  简单的模型:

    public partial class TestContext : DbContext
{
public TestContext()
{
} public TestContext(DbContextOptions<TestContext> options)
: base(options)
{
} public virtual DbSet<User> User { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
optionsBuilder.UseSqlServer("Data Source=.;Initial Catalog=Test;Integrated Security=True");
}
} protected override void OnModelCreating(ModelBuilder modelBuilder)
{}
}

  使用模型操作数据库:

    public class HomeController : Controller
{
private DataContext _context;
public HomeController(DataContext context)
{
_context = context;
}
public IActionResult Index()
{
_context.User.Add(new User() { Name="name",Password=""});
_context.SaveChanges();
//查询
var users = _context.User.ToList();
return View();
}

3.Code First

  Code First 也就是通过EF迁移来完成从模型生成数据库。

  1.创建项目

  创建一个ASP.NET Core WEB 应用程序

  

  

  2.打开NuGet包管理器下载 Microsoft.EntityFrameworkCore.SqlServer 和 Microsoft.EntityFrameworkCore.Tools

  3.在Models文件夹创建实体类和上下文类

public class BlogContext:DbContext
{
public BlogContext(DbContextOptions<BlogContext> options)
: base(options)
{
} public DbSet<Blog> Blog { get; set; }
public DbSet<Post> Post { get; set; }
}

  

    public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public virtual List<Post> Posts { get; set; }
}

  

    public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
}

  

  4.在ConfigureServices方法中添加上下文依赖注入:

public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
}); var connectionString = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<BlogContext>(options =>
options.UseSqlServer(connectionString)); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

  5.在appsettings.json中添加链接数据库字符串

{
"ConnectionStrings": {
"DefaultConnection": "Data Source=.;Initial Catalog=Blog;Integrated Security=True"
},
"Logging": {
"LogLevel": {
"Default": "Information"
}
},
"AllowedHosts": "*"
}

  

  6.打开NuGet程序包管理控制台,先输入 Add-Migration FirstMigration,在输入pdate-Database。迁移成功后,会创建数据库,以及会在项目中生成一个Migrations文件夹,里面时迁移记录。

  

  创建成功就可以通过构造函数依赖注入的方式访问数据库了。

4.Database First

  Database First,也就是通过现有数据库生成模型

  1.创建项目,并安装Microsoft.EntityFrameworkCore.SqlServer , Microsoft.EntityFrameworkCore.Tools 和 Microsoft.EntityFrameworkCore.SqlServer.Design

  2.在NuGet程序包管理器控制台输入:Scaffold-DbContext "Data Source=.;Initial Catalog=Blog;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer 。执行成功会生成相关模型:

  

  3,现在可以使用上下文访问数据库了,但是不能通过依赖注入的方式。如果需要,还是在ConfigureServices方法中添加代码:services.AddDbContext<BlogContext>()。如果要使用appsettings.json中的连接字符串,就需要按照上面ConfigureServices方法中所写的。

  

最新文章

  1. php调用COM组件
  2. USB驱动开发大全【转】
  3. Python-类变量,成员变量,静态变量,类方法,静态方法,实例方法,普通函数
  4. GoogleNet tips
  5. Java 动态代理
  6. iOS后台定位,实时向服务器发送最新位置
  7. [SAP ABAP开发技术总结]动态修改选择屏幕
  8. JavaScript js 精确、保留小数方法
  9. 【BZOJ】【1103】【POI2007】大都市meg
  10. Ci框架整合smarty模板引擎
  11. while +next 循环 回到循环顶端
  12. 如何在Latex上裁减图片
  13. 【Netty源码分析】数据读取过程
  14. rpc和http
  15. POJ 3278 Catch That Cow(赶牛行动)
  16. Qt程序关于路径、用户目录路径、临时文件夹位置获取方法
  17. JAVA-错误Several ports (8080, 8009) required by Tomcat v7.0 Server at localhost are already in use.
  18. [转] handsontable的核心方法
  19. 《Effective Java 第二版》读书笔记
  20. poj2176 Folding【区间DP】

热门文章

  1. MS17-010漏洞利用复现
  2. [MySQL] 为什么要给表加上主键
  3. Python元组与字符串操作(9)——随机数、元组、命名元组
  4. Python 大佬 的经典设计格言 ---- 铭记于心
  5. E09【餐厅】Can I have the bill,please?
  6. HttpWatch功能详细介绍
  7. Spring Cloud Alibaba Sentinel 的配置选项:spring.cloud.sentinel.transport.port,默认值:8719
  8. django+uwsgi+nginx 导出excel超时问题
  9. java 随笔
  10. [LeetCode] 272. Closest Binary Search Tree Value II 最近的二分搜索树的值之二