zoukankan      html  css  js  c++  java
  • 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,在输入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方法中所写的。

      

  • 相关阅读:
    hibernate 总结
    事物随笔
    添加收藏夹的作法
    jquery uploadify多文件上传
    过滤器与拦截器的区别
    网站首页添加缓存--------ehcache的简单使用
    DWR 在项目中的应用
    分页标签:pager-taglib的使用
    关闭iptables(Centos)
    Centos移除图形界面
  • 原文地址:https://www.cnblogs.com/afei-24/p/11012886.html
Copyright © 2011-2022 走看看