Entity Framework not only facilitates operation, but also considers user friendly interaction. The perfect combination of ef4.0 and vs2010 is also a reason for us to choose it. Compared with Nhibernate Microsoft, this is indeed a good job.
The following is a simple example of codefirst.
We are still following the previousArticleEntity Framework Quick Start -- create a console project like an instance.
Step 1: Create a console Project
Step 2: Right-click the project and add the ADO. Net object data model.
:
Step 3: select the method for generating the object "Empty model"
:
Step 4: Add EF entities
Drag an object from the toolbar to the edmx designer and name it student. Then, on the property page, modify the object set name of this object as student and add two scalar property names, age [complex attributes and navigation attributes will be introduced in the following article], as shown in:
Step 5: generate a database based on the model
Note: Right-click the edmx blank area, select generate database based on the model, and select the database connection we want to create. As shown in:
Click "OK" and click "Next". The generated SQL statement based on the model is displayed. On the generated SQL page, right-click and execute the SQL statement, as shown in:
Check that schooldb and student have been created for us in the database, as shown in:
This is a great pleasure. This automation tool is indeed very easy to use and enjoys such silly operations provided by Microsoft.
Step 6: Use EF to insert a piece of data
First, let's take a look at what EF automatically generates.Code: It mainly refers to Database Access Gateway and entity class student, as shown in:
Then add the following code and execute
Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. text;
Namespace Efcodefirst
{
Class Program
{
Static Void Main ( String [] ARGs)
{
Using (Schoolcontainer schoolentities = New Schoolcontainer ())
{
// Create a student instance
Student Stu = New Student {age = 23 , Name = " Flydragon " };
// Put the above instance into the entity set corresponding to the Gateway
Schoolentities. Student. addobject (Stu );
// Persistent to Hard Disk
Schoolentities. savechanges ();
}
Console. writeline ( " OK " );
}
}
ProgramRun successfully. View the database:
The result is correctly executed.
To sum up, I will first add an entity model, then add an entity class above, and generate a database directly based on the SQL generated by the model, then, you can directly use the objectcontext generated by EF and the database entity student to directly operate the database table. This is also an attractive part of codefirst programming.
What Microsoft can do so conveniently and easily is indeed admirable!
Entity Framework Quick Start-index stickers