In the old Entity Framework, developers can generate business entity models from existing databases. This development method is called database-driven development method. In the Entity Framework of 4.1, a developer is allowed to create an entity business class before generating related database files. This development method can be called"CodeDevelopment Method. This method is very beneficial to developers. First, developers will build entity models in business logic from the perspective of Object-oriented thinking, generating database files based on actual needs is a real object-oriented method.
To use Entity Framework 4.1 in this article, the following address provides the 4.1 installation package download: http://down.qiannao.com/space/file/huwlnew/share/2011/8/9/EntityFramework4.1_-4e92-8054-529b-91cf.rar/.page
Or you can use nuget for online installation and select the following menu:
Enter PM> install-package efcodefirst in the lower-end console of vs2010.
The following is displayed, indicating that the installation is successful:
The example in this article will create two types of invoice class and lineitem class. The database generated in this article is named accounting, and two tables are generated: invoice and lineitem. The functions in the example also include adding, deleting, modifying, and querying the data in the database in the gridview. Finally, they will demonstrate how to change the corresponding database if the class has changed.
Step 1
1) Start vs.net 2010;
2) create an Asp.net web project in C # language;
3) Name the project ef4codefirst;
4) in the project explorer, right-click a class and name it invoice. CS.
The code for modifying this class is as follows:
Public class invoice
{
Public int ID {Get; set ;}
Public datetime invoicedate {Get; set ;}
Public double total {Get; set ;}
}
In our class, the ID attribute exists. The entity framework generates the corresponding field ID in the database table based on the ID attribute. If the ID attribute is not defined in the class, the field named "class file name + id" is generated in the database table file.
In this invoice class, there are multiple lineitems, which clearly constitute a one-to-many relationship between them, so we first establish a lineitem class.
5) Add a lineitem class with the following code:
Public class lineitem
{
Public int ID {Get; set ;}
Public String productname {Get; set ;}
Public double itemcost {Get; set ;}
Public double units {Get; set ;}
Public invoice {Get; set ;}
}
In this class, the reference to the invoice class is maintained, and the invoice class is also associated.
6) in the invoice class, the lineitem class reference should also be added. Here, the collection class is used, and the following code is used:
Public icollection <lineitem> lineitems {Get; set ;}
At the same time, the lineitem class should be initialized in the invovice class constructor, as follows:
Public invoice ()
{
Lineitems = new list <lineitem> ();
}
After completing the preceding steps, the Entity Framework can create related databases and tables from the entity class. Next, proceed to step 2.
Step 2
Next, we will reference the class library file of the Entity Framework to our project.
1) in the project explorer, right-click the project name and select "add reference" in the pop-up menu ".
2) Select system. Data. entity and click OK.
3) Add a new class for the project, name it accounting. CS, and modify the Code as follows:
Using system. Data. entity;
Public class accounting: dbcontext
{
Public dbset <invoice> invoices {Get; set ;}
Public dbset <lineitem> lineitems {Get; set ;}
}
As you can see, this class inherits the dbcontext class, which is actually a tool class of entity, which encapsulates many useful APIs. In the accounting class, there are two instances of dbset classes respectively, they represent the two tables to be generated in the database.
4) Then you need to add a database connection in Web. config, as shown below:
<Add name = "accounting"
Providername = "system. Data. sqlclient"
Connectionstring = "Data Source = (local); initial catalog = accounting; Integrated Security = sspi;"/>
5) Add the gridview control in default. aspx and write the following code:
Using system. Data. entity;
Protected void page_load (Object sender, eventargs E)
{
Accounting DB = new accounting ();
DB. invoices. Load ();
Gridview1.datasource = dB. invoices. Local. tobindinglist ();
Gridview1.databind ();
}
Remember to introduce system. data. entity class library, instantiate the instance dB of the accounting object, and call its load method to load all invoice data (Here we generally load one-to-many data ).
6) after running the project, you will find that there are three tables in SQL Server: Invoice table and lineitem table, and ed1_adata table, the Entity Framework is automatically generated for us and stores the metadata in the database. In addition, we can see that in the lineitem table, the Entity Framework has automatically generated the foreign key invoice_id for us.
Step 3
Now that the database has been created, you can add some data to it. Add the following code in page_load:
Protected void page_load (Object sender, eventargs E)
{
Accounting DB = new accounting ();
Invoice invoice = new invoice
{
Invoicedate = datetime. Now,
Total = 1000
};
DB. invoices. Add (invoice );
DB. savechanges ();
DB. invoices. Load ();
Gridview1.datasource = dB. invoices. Local. tobindinglist ();
Gridview1.databind ();
}
Here we instantiate an instance of the invoice class, add relevant data content, and then use dB. invoices. add to the dbset attribute of the account class, and call the savechanges method to save it to the database. After running the command, you can see the following results:
Now let's try to update the data. The Code is as follows:
Protected void page_load (Object sender, eventargs E)
{
Accounting DB = new accounting ();
Invoice invoice = new invoice
{
Id = 1,
Invoicedate = datetime. Now,
Total = 900
};
DB. Entry (invoice). State = entitystate. modified;
DB. savechanges ();
DB. invoices. Load ();
Gridview1.datasource = dB. invoices. Local. tobindinglist ();
Gridview1.databind ();
}
Here, the ID of the invoice instance member variable is changed to 1. Note that when updating, the status (State) is set to entitystate. modified indicates that the record is modified, and then saved. After running, you can see that the data in the database is indeed updated. All these are the functions of the Entity Framework.
Finally, we learned to delete records. The Code is as follows:
Protected void page_load (Object sender, eventargs E)
{
Accounting DB = new accounting ();
Invoice invoice = new invoice
{
Id = 1,
Invoicedate = datetime. Now,
Total = 900
};
DB. invoices. Remove (invoice );
DB. savechanges ();
DB. invoices. Load ();
Gridview1.datasource = dB. invoices. Local. tobindinglist ();
Gridview1.databind ();
}
You only need to call the Remove Method to delete the record in the database.
Step 4
In this step, we will learn how to change the data model. If we want to add a tax attribute to the invoice class, we also need to add this field to the database by using the Entity Framework. The following shows the procedure:
1) we add the tax attribute to the invoice class.
2) if you run the project at this time, the following error message is displayed:
The model backing the 'accounting' context has changed since the database was
Created. either manually delete/update the database, or call
Database. setinitializer with an idatabaseinitializer instance. For example,
Dropcreatedatabaseifmodelchanges strategy will automatically delete and recreate
The database, and optionally seed it with new data.
The prompt tells us, or manually delete the database or use the code method at this time. We can use the code method to complete the operation. We only need to encode the following in the application_start event, the Entity Framework automatically reflects the newly added attributes to the database:
Void application_start (Object sender, eventargs E)
{
// Code that runs on application startup
System. Data. entity. database. setinitializer <accounting>
(New system. Data. entity. dropcreatedatabaseifmodelchanges <accounting> ());
}
3) run the project again. The tax field is added to the data table.
Step 5
Note: In Step 4 above, if the attributes of the class change, the code is used to drop the old database and create a new database. This is time-consuming and laborious, however, we can use another method to add test data during initialization. In this way, the test data is automatically added every time the database is re-created, the solution is as follows:
1) Add a new class named accountinginitializer. CS in the project.
2) modify the Code as follows:
Public class accountinginitializer:
System. Data. entity. dropcreatedatabaseifmodelchanges <accounting>
{
Protected override void seed (accounting context)
{
Invoice invoice = new invoice {Total = 20, invoicedate =
New datetime (2011, 4, 14), tax = 1.50 };
Invoice. lineitems. Add (New lineitem
{Itemcost = 2, productname = "test", Units = 4 });
Invoice. lineitems. Add (New lineitem
{Itemcost = 4, productname = "Test 2", Units = 3 });
Context. invoices. Add (invoice );
Context. savechanges ();
Base. Seed (context );
}
}
Specifically, this class inherits the dropcreatedatabaseifmodelchanges class and overwrites the seed method. You can write new test data in this method. Remember to write the following code in the application_onstart event:
void application_start (Object sender, eventargs e)
{< br> // execute this code during startup
system. data. entity. database. setinitializer
(New accountinginitializer ();
}