Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

EntityFramework, a simple entrance.

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

In any data-related system, data persistence is a problem that can not be ignored.

For a long time, Java platform has produced many ORM frameworks of NB, such as Hibernate, MyBatis and so on. On the. Net platform, there has never been a single piece of the ORM framework that allows almost all developers to change the habit of accessing databases with spelled SQL statements.

In fact, on the .NET platform, there are a lot of similar things emerging one after another, such as Nhibernate, Ibatis, and Microsoft's own son, the cheating LinqToSQL. Although there are so many frameworks, I have never seen that the ORM framework on the .NET platform is as popular as in Java.

Fortunately, Microsoft produced another son-EntityFramework. The previous versions have not been used. I learned about version 6.1.3 directly a few days ago. Feel, really TMD easy to use.

In view of the fact that all the tutorials on the Internet are too dogmatic and look foolish at the beginning, I will take this experience as an essay for everyone to study and discuss together.

I. installation framework

First, add the environment. Right-click the project and you can install it directly in NuGet. As shown below:

After the installation is completed, two references about EntityFramework have been added to the project reference, as shown below:

At this point, the environment is ready.

Second, create Context class and model class

0, prepare the database.

Before we can write code, we need to have a test database and a test table.

I use SQLServer here, and the table structure is as follows:

There are three modes for using EF: Model First, DataBase First, and Code First. What is the difference between these First? I haven't studied carefully. But I seem to be using a project built by Code First here. This way, I just feel convenient, easy to use, feel the project is cleaner, do not have to add messy code and configuration.

1, add a model class.

Model classes in EF, like ordinary classes, are nothing more than adding attribute tags to classes or attributes to map table relationships. As follows:

[Table ("Users")] public class UserInfo {[Key] [StringLength (20)] [Column ("Code")] public string Code {get; set;} [StringLength (20)] public string Name {get; set;}}

In the above code, the following key information is defined:

1. Class UserInfo corresponds to the Users table in the database.

2the Name Code attribute corresponds to the Code field in the database (if the property name is the same as the field name, you can ignore this configuration, such as the Code attribute).

3, and indicates that the length of two character-type attributes cannot exceed 20 characters.

4, indicating that the column corresponding to the Code property is a primary key column.

(note: Table, Key, StringLength, Column classes need to refer to the namespaces System.ComponentModel.DataAnnotations and using System.ComponentModel.DataAnnotations.Schema)

2, add the DbContext class.

DbContext class is the core of EF, which encapsulates all the logic related to data access business. No matter whether it is addition, deletion, modification, query or transaction, all the business of database operation can be done here. That sounds awesome!

It sounds great, but it's actually even better!

Although very powerful, but it is super easy to use. For example, code like the following implements a simple DbContext class:

Public class DALContext: DbContext {public DALContext (): base ("name=DALContext") {} public virtual DbSet Users {get; set;} protected override void OnModelCreating (DbModelBuilder modelBuilder) {}}

A few lines complete the complex DB operation.

The above code briefly illustrates:

1. This class has its own name. It can be called whatever you want. My name here is DALContext.

2. This class must inherit the DbContext class.

3. In the constructor, call the constructor of the parent class to indicate how to connect to the database, which can be either the connection string or the connection name configured in the configuration file (the connection name must be prefixed with name=).

The properties of the DbSet type declared by 4jure virtual encapsulate a lot of business logic for data manipulation, and we only need to manipulate this attribute.

5. If you have several tables, just declare a few properties of type DbSet. T is the Model declared in the previous code, and the property name is chosen at will.

What is the use of the OnModelCreating method? I don't know exactly.

(this class references the namespace System.Data.Entity)

3, configure the connection string

Open the configuration file and add a connection string configuration named DALContext. As shown below:

Open the configuration file and we will find that there is something strange about entityFramework in it. As for whether it is necessary and whether people will die if deleted, I don't know.)

At this point, the mapping of the database table is Ok.

Third, write test code

Don't talk nonsense, put the code:

Static void Main (string [] args) {using (DALContext db = new DALContext ()) {try {db.Users.Add (new UserInfo () {Code = DateTime.Now.Ticks.ToString (), Name = "Zhang San"}) IEnumerable users = db.Users.Where (u = > u.Name = "Zhang San"); foreach (var u in users) {Console.WriteLine (string.Format ("{0}-{1}", u.CodeMagi u.Name));} db.SaveChanges () } catch (Exception ex) {Console.WriteLine (ex.Message);}} Console.WriteLine ("Press any key to exit"); Console.ReadKey ();}

In the Main method, we declare a DALContext object db, which is wrapped with using to facilitate the release of object resources.

This code implements the following functions:

1. Access the Users property of the db object and use the Add method to add a record to the database table as if it were a collection.

2, access the Users property of the db object, use the Where method to query a batch of data objects according to the conditions, save them in the variable users, and loop output to the console.

3. Use the SaveChanges method of the db object to commit changes to the database.

After running, the results are as follows:

The above example implements the add and query functions, delete and modify functions are similar to operation collections, as long as you make sure that the SaveChanges method is finally called to submit the changes.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report