当前位置:网站首页>EF core Basics

EF core Basics

2022-06-26 03:44:00 yuyue5945

EF Core Introduction to basics

EF Core Basic concepts

Concept

EF Core The full name is Entity Framework Core, You can use EF Core Development oriented .NET Core Application ,EF Core At the same time support in Visual StudioVisual Studio for Mac or Visual Studio Code And so on . although EF CORO We also support the Xamarin and .Net Native On the implementation of running , But there are operational limitations , May affect EF Core The efficiency of processing , Not recommended for the time being .

Technical outline

Entity Framework (EF) Core It's lightweight 、 Scalable 、 Common use of open source and cross platform versions Entity Framework Data access technology .

EF Core Can be used as an object relational mapper (O/RM), This can achieve the following two points :

  • send .NET Developers can use .NET Object processing database .
  • No need to write most of the data access code as usual .

EF Core Support multiple database engines .

obtain Entity Framework Core Runtime

give an example : Install or update EF Core SQL Server Way

Three ways

  • NET Core CLI ( The console command line operation page is executable )
    • perform “dotnet add package Microsoft.EntityFrameworkCore.SqlServer” The order
    • have access to -v Modifiers in dotnet add package The command specifies the specific version . for example , If you want to install EF Core 2.2.0 package , Please put -v 2.2.0 Append to command .
  • Visual Studio NuGet Package Manager dialog
    • from Visual Studio From the menu “ project ”>“ management NuGet package ”
    • single click “ Browse ” or “ to update ” tab
    • To install or update SQL Server Provider , Please select Microsoft.EntityFrameworkCore.SqlServer Pack and confirm .
  • Visual Studio NuGet Package manager console
    • from Visual Studio From the menu “ Tools ”>“NuGet Package manager ”>“ Package manager console ”
    • Install-Package Microsoft.EntityFrameworkCore.SqlServer
    • To update a provider , Use Update-Package command .
    • To specify a specific version , have access to -Version Modifier . for example , If you want to install EF Core 2.2.0 package , Please put -Version 2.2.0 Append to command .

EF CORE Practical content

Model

about EF Core, Use the model to perform data access . The model consists of entity classes and context objects representing database sessions DBContext constitute . Context objects allow you to query and save data .

EF Support the following model development methods :

  • Generate models from existing databases .
  • Code the model manually , Make it conform to the database .
  • After creating the model , Use EF Migration creates a database from the model . When the model changes , Migration allows databases to evolve .

EF An important element in DBContext

DbContext It is the bridge between entity class and database ,DbContext Mainly responsible for data interaction , The main role :

  • DBContext Contains the set of entities that are mapped to the database 【DbSet<TEntity>
  • DBContext take LINQ TO Entities The query is converted to DBServer cognitive SQL sentence
  • DBContext Track the changes of entities after they are queried from the database
  • DBContext Support persistent database

As shown in the figure below
20201224205010-2020-12-24

DBContext Detailed introduction

DBContext It is an implementation of the above functions , The natural class is bigger , The interception method is shown below :

20201224205741-2020-12-24

Here's a piece of code for better understanding :


using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;

namespace Intro
{
    
    public class BloggingContext : DbContext
    {
    
        public DbSet<Blog> Blogs {
     get; set; }
        public DbSet<Post> Posts {
     get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
    
            optionsBuilder.UseSqlServer(
                @"Server=(localdb)\mssqllocaldb;Database=Blogging;Integrated Security=True");
        }
    }

    public class Blog
    {
    
        public int BlogId {
     get; set; }
        public string Url {
     get; set; }
        public int Rating {
     get; set; }
        public 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; }
    }
}

Inquire about

Using language to integrate queries (LINQ) Retrieve instances of entity classes from the database . among ,where and Orderby Both methods do not perform database operations Let's focus on , Only ToList This operation , Will actually go to the database to execute the query .

using (var db = new BloggingContext())
{
    
    var blogs = db.Blogs
        .Where(b => b.Rating > 3)
        .OrderBy(b => b.Url)
        .ToList();
}

Save the data

Create in the database using an instance of an entity class 、 Delete and modify data .

using (var db = new BloggingContext())
{
    
    var blog = new Blog {
     Url = "http://sample.com" };
    db.Blogs.Add(blog);
    db.SaveChanges();
}

EF O/RM matters needing attention

although EF Core Good at extracting a lot of programming details , But there are still some that apply to any O/RM Best practices for , Can help avoid common pitfalls in production applications :

  • To build in high performance production applications 、 debugging 、 Analyze and migrate data , Must have intermediate knowledge of basic database server or higher level knowledge . for example , About primary and foreign keys 、 constraint 、 Indexes 、 Standardization 、DML and DDL sentence 、 data type 、 Knowledge of analysis, etc .
  • Functional and integration testing : Be sure to copy the production environment as closely as possible , In order to :
    • Find problems that only occur when using a specific version of the database server .
    • The upgrade EF Core And other dependencies . for example , Add or upgrade ASP.NET Core、OData or Automapper Other framework . These dependencies can affect EF Core.
  • Performance and load tests are representative . Immature usage of some functions, poor scalability . for example , Multiple sets contain content 、 Heavy use of delayed loading 、 Perform conditional queries on unindexed Columns 、 Large scale update and insertion of values generated by storage 、 Lack of concurrent processing 、 Large model 、 Insufficient caching policy .
  • Safety review : for example , Connection strings and other confidential processing 、 Database permissions for non deployment operations 、 original SQL Input validation for 、 Sensitive data encryption .
  • Ensure that logging and diagnostics are adequate and available . for example , Proper logging configuration 、 Query tags and Application Insights.
  • Error recovery . For common fault scenarios ( Such as the version back 、 Back off the server 、 Scale out and load balance 、DoS Mitigation and data backup ) Prepare contingency plans .
  • Application and migration . Plan how to apply migration during deployment ; Performing this operation at application startup can cause concurrency problems , And for normal operation , It's more necessary than that . During migration , Use staging to assist recovery from errors . For more information , See application migration .
  • Detailed inspection and testing of generated migrations . Before applying migration to production data , It should be fully tested . If the table contains production data , The shape and column type of the schema cannot be easily changed . for example , stay SQL Server On , For columns mapped to strings and decimal attributes ,nvarchar(max) and decimal(18, 2) It's rarely the best type , But these are EF Default value used , because EF I don't know about you .

Blogger GitHub Address

https://github.com/yuyue5945

Pay attention to the official account

 official account

原网站

版权声明
本文为[yuyue5945]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202180546225131.html