EF Core基础入门教程

2022-04-18 19:04:31

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

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

Microsoft SQL SeverSQLiteNpgsqlmysql......

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<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 SecbyVZWGwPxjurity=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 应用程序

EFCore基础入门教程

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

EFCore基础入门教程

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文件夹,里面时迁移记录。

EFCore基础入门教程

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

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 。执行成功会生成相关模型:

EFCore基础入门教程

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

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