EF Core基础入门教程

这篇文章介绍了EF Core的基础入门教程,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

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

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

  • Microsoft SQL Sever
  • SQLite
  • Npgsql
  • MySQL
  • ......

1.获取EF Core

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

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

2.模型

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

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

简单的模型:

    public partial class TestContext : DbContext { public TestContext() { } public TestContext(DbContextOptions options) : base(options) { } public virtual DbSet 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="123"}); _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 options) : base(options) { } public DbSet Blog { get; set; } public DbSet Post { get; set; } }
public class Blog { public int BlogId { get; set; } public string Url { get; set; } public virtual List 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(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(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,再输入Update-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()。如果要使用appsettings.json中的连接字符串,就需要按照上面ConfigureServices方法中所写的。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持0133技术站。

以上就是EF Core基础入门教程的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » ASP编程