EF introduction

EF is Entity Framework. It is an official Object Relational Mapping (ORM) tool provided by Microsoft. ORM enables developers to save database access code time and spend more time on business logic layer code. EF provides change tracking, unique constraints, lazy loading, querying things, and more. Developers use Linq to operate databases as easily as objects.

EF has three usage modes :1. Code First mode: generate database structure from entity class; 2. Model First mode: design database and generate entity class through database visual designer; 3. Database First: Entity classes are generated by the Database.

Code First mode

The Code First mode is what we call the “Code First” mode, and is a new feature added from EF4.1. When using Code First for EF development, developers simply write the corresponding data classes (which are the implementation of the domain model) and automatically generate the database. The advantage of this design is that we can do all the data manipulation against the conceptual model without having to worry about the storage relationship of the data, making it more natural to adopt an object-oriented approach to data-oriented application development.

Use Code First mode:

Create a new console application called EFDemo in Vs2017. Create a user class and a UserContext class:

The User class:

using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; Namespace EFDemo {public class User {[Key,Index]// Set Id as primary Key and add Index public int Id {get; set; } public string Name { get; set; } public string Password { get; set; }}}Copy the code

UserContext class:

using System.Data.Entity; namespace EFDemo { public class UserContext :DbContext{ public UserContext() : base("EFDemoConnectionString") { } public DbSet<User> User { get; set; }}}Copy the code

In establishing UserContext must inherit from System. Data. The Entity. The DbContext class, to have the Data of CRUD operations, to use the DbContext class must reference EntityFramework package. Retrieval installation in NuGet:

As follows:

After running the Main method, the database is automatically generated:

using System; using System.Linq; namespace EFDemo { class Program { static void Main(string[] args) { using(var context = new UserContext()) { var user =  new User { Id = 1, Name = "user", Password = "123", }; context.User.Add(user); // Add a new data context.savechanges (); Var query = from a in context.User where a. id == 1 select a; Console.Write($"UserId:{user.id},UserName:{user.name},UserPassword:{user.password}"); Console.ReadKey(); }}}}Copy the code

Results show:

Database display: