EntityFramework simple entry, entityframework
In any data-related system, data persistence is a problem that cannot be ignored.
For a long time, the Java platform has developed a lot of nb orm frameworks, such as Hibernate and MyBatis .. On the. NET platform, the orm framework has never been used by almost all developers to get rid of the habit of using spelling SQL statements to access the database.
In fact, on the. NET platform, a lot of similar things are emerging, such as nhib.pdf, Ibatis, and LinqToSQL, a close son of Microsoft. Although there are so many frameworks, I have never seen the. NET platform's ORM frameworks become as popular as those in Java.
Fortunately, Microsoft has developed another son, EntityFramework. I have never used the previous versions. I learned about version 6.1.3 a few days ago .. It feels like TMD is easy to use ..
In view of the fact that all the tutorials on the Internet are too well-taught and seem very boring at the beginning, I will take this article as an example for everyone to learn and discuss.
I. Installation framework
First, add the environment. Right-click the project and you can directly install it in NuGet. For example:
Now, the environment is configured.
Ii. Create Context class and model class
0. Prepare the database.
Before writing code, we must first have a test database and a test table.
Here I use SQLServer. The Table structure is as follows: [Table ("Users")] public class UserInfo {[Key] [StringLength (20)] [Column ("Code")] public string Code {get; set;} [StringLength (20)] public string Name {get; set ;}}
The code above defines the following key information:
1. The UserInfo class corresponds to the Users table in the database.
2. The Code attribute corresponds to the Code field in the database (if the attribute Name and field Name are the same, you can ignore this configuration, such as the Name attribute ).
3. The length of the two character attributes cannot exceed 20 characters.
4. indicates that the column corresponding to the Code attribute is a primary key column.
(Note: for the Table, Key, StringLength, and Column classes, the namespace System. ComponentModel. DataAnnotations and using System. ComponentModel. DataAnnotations. Schema must be referenced)
2. Add the DbContext class.
The DbContext class is the core of EF and encapsulates all data access business-related logic. Whether it's adding, deleting, modifying, querying, or transactions, all database operations can be done here .. It sounds awesome!
It sounds awesome. In fact, it's even more awesome!
Although awesome, it is super easy to use. For example, the following code implements a simple DbContext class:
public class DALContext : DbContext { public DALContext() : base("name=DALContext") { } public virtual DbSet<UserInfo> Users { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { } }
A few lines have completed complex DB operations.
The above code briefly describes:
1. The class name is self-defined. What is the name of this class? I'm DALContext here.
2. This class must inherit the DbContext class.
3. In the constructor, call the constructor of the parent class to specify how to connect to the database. Here it can be a connection string, it can also be the connection name configured in the configuration file (the connection name must be prefixed with name = ).
4. the attribute of the virtual declared DbSet <T> type encapsulates the business logic of a lot of data operations. We only need to operate on this attribute.
5. If there are several tables, just declare the attributes of several DbSet <T> types. T is the Model declared in the previous code. The attribute name can be set as needed.
6. What is the use of the OnModelCreating method? I don't know either.
(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. For example:
3. Write test code
Don't talk nonsense, go to the Code:
Static void Main (string [] args) {using (DALContext db = new DALContext () {try {db. users. add (new UserInfo () {Code = DateTime. now. ticks. toString (), Name = "James"}); IEnumerable <UserInfo> users = db. users. where <UserInfo> (u => u. name = "Zhang San"); foreach (var u in users) {Console. writeLine (string. format ("{0}-{1}", u. code, 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. To facilitate the release of object Resources, we use using to package it.
This Code provides the following functions:
1. Access the Users attribute of the db object. Use the Add method to Add a record to the database table just like a set.
2. Access the Users attribute of the db object, use the Where method to query a batch of Data Objects Based on the condition, save them in the users variable, and output them cyclically to the console.
3. Use the SaveChanges method of the db object to submit changes to the database.
After running, the result is as follows:
In the preceding example, the ADD and query functions are implemented. The Delete and modify functions are similar to the operation set. You only need to ensure that the SaveChanges method is called to submit the modifications.