EF Core using simple introduction

  EF Core is an ORM (object-relational mapping), which allows .NET developers can use the .NET object database operation, avoid like ADO.NET code to access the database, developers only need to write to the object.

  EF Core supports a variety of database engines:

    Microsoft SQL Sever

    SQLite

    Npgsql

    MySQL

    ......

1. Obtain EF Core

  Get support database to be used by NuGet. For example: Microsoft SQL Sever

  Open NuGet Package Manager console, type: Install-Package Microsoft.EntityFrameworkCore.SqlServer

2. Model

  EF Core database is accessed through a model. Model consists of entity classes and represented in the database session component, and allows you to query and save the data derived context.

  May be generated from an existing database model may be used to complete the migration EF generated from the model database, i.e. Database First and Code First.

  Simple model:

    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)
        {}
    }

  Operation using the model database:

    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

   EF Code First is through migration to complete the database generated from the model.

  1. Create a project

  Creating a ASP.NET Core WEB application

  

  

  2. Open the package manager to download Microsoft.EntityFrameworkCore.SqlServer NuGet and Microsoft.EntityFrameworkCore.Tools

 

  3. Create entity classes and context class file folders in 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. Add ConfigureServices context dependency injection process:

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. Add the link database string appsettings.json

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

  

  6. Open NuGet package management console, to enter Add-Migration FirstMigration, input pdate-Database. After the migration is successful, it will create a database, and generates a Migrations folder in the project, migration recorded inside.

  

  You can access the database successfully created dependency injection by way of a constructor.

 

4.Database First

  Database First, i.e. by generating a model of an existing database

  1. Create a project and install Microsoft.EntityFrameworkCore.SqlServer, Microsoft.EntityFrameworkCore.Tools and Microsoft.EntityFrameworkCore.SqlServer.Design

  2. NuGet Package Manager console input: Scaffold-DbContext "Data Source = .; Initial Catalog = Blog; Integrated Security = True" Microsoft.EntityFrameworkCore.SqlServer. The successful implementation of the relevant model generates:

  

  3, can now access the database using the context, but not by way of dependency injection. If necessary, add code or ConfigureServices method: services.AddDbContext <BlogContext> (). To use the connection string appsettings.json, it is necessary in accordance with the above method ConfigureServices written.

  

 

Guess you like

Origin www.cnblogs.com/afei-24/p/11012886.html