当前位置:网站首页>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
DBContext Detailed introduction
DBContext It is an implementation of the above functions , The natural class is bigger , The interception method is shown below :
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
边栏推荐
- 上传文件/文本/图片,盒子阴影
- General operations of asynctask
- You cannot call Glide. get() in registerComponents(), use the provided Glide instance instead
- 解决uniapp插件robin-editor设置字体颜色和背景颜色报错的问题
- JS array array JSON de duplication
- Route jump: click the operation button of the list to jump to another menu page and activate the corresponding menu
- 2022.6.25-----leetcode.剑指offer.091
- Uni app custom selection date 2 (September 16, 2021)
- The role of children's programming in promoting traditional disciplines in China
- todolist未完成,已完成
猜你喜欢
Classic model - Nin & googlenet
Solve the problem that the uniapp plug-in Robin editor reports an error when setting the font color and background color
多媒体元素,音频、视频
MySQL高级篇第一章(linux下安装MySQL)【下】
After Ali failed to start his job in the interview, he was roast by the interviewer in the circle of friends (plug)
“再谈”协议
Can string be changed?
Nebula Graph学习篇3_多线程完成6000w+关系数据迁移
The role of children's programming in promoting traditional disciplines in China
Non H5 end of uni app, regional setting of status bar on the top of mobile phone
随机推荐
HL7Exception: Can‘t XML-encode a GenericMessage. Message must have a recognized struct
动态线段树leetcode.715
Insect structure and Deconstruction
C # knowledge structure
Click event
Using meta analysis to drive the development of educational robot
ASP. Net startup and running mechanism
解决uniapp插件robin-editor设置字体颜色和背景颜色报错的问题
Popupwindow utility class
progress bar
Classic model alexnet
MySQL addition, deletion, query and modification (Advanced)
MySQL advanced part (IV: locking mechanism and SQL optimization)
优化——多目标规划
After Ali failed to start his job in the interview, he was roast by the interviewer in the circle of friends (plug)
Graphics card, GPU, CPU, CUDA, video memory, rtx/gtx and viewing mode
Cliquez sur le bouton action de la liste pour passer à une autre page de menu et activer le menu correspondant
Group counting notes - instruction pipeline of CPU
Prism framework
js实现文字跑马灯效果