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-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="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<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,再输入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<BlogContext>()。如果要使用appsettings.json中的连接字符串,就需要按照上面ConfigureServices方法中所写的。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析