Entity Framework 4.0 and 4.1

Source: Internet
Author: User
Tags generator generator
I remember paying attention to entity from the beginning of last year.
Framework. At that time, it was just a simple test and found that it was not very mature than nhib.pdf. At that time, EF was mainly developed in table-Driven Mode and relied heavily on EDM files. In addition, the data layer coupled with the model layer made some MVC users suffer. From the oxite1 project to the oxite2 project, Microsoft had to worry about the unclear relationship between the dal and the model.
Directly implement BLL Based on EDM. Because the entityobject model is coupled with objectcontext, if entityobject is directly provided to the client in the n-layer architecture, objectcontext will also be called on the client, therefore, this problem can only be solved through the DTO object method. After all, most entityobjects can be directly transmitted and used instead of being passed through DTO. Let's take a look at the progress of ef4.0 and ef4.1. First, Let's explain some terms. EDM is an XML file for ing object data relations. Different from nhib.pdf, each object is mapped to an XML file. EDM consists of three parts:
CSDL, SSDL, and MSL. On the surface of CSDL, the object data model structure is displayed. SSDL represents the corresponding data storage architecture. The relationship between the CSDL object and the SSDL data structure is implemented through MSL ing. EDM is implemented through ADO. net
Object Data Model generation
There are two ways to generate an EDM file: one is based on a database and the other is to create an empty EDM model. The former is the database to be mentioned later
The first method. The latter is the model first method. Code is generated for the created EDM model. The generated code is different depending on the tool used to generate the code. Let's take a look at the following generation methods, which are all generated based on the EDM model. The method of the initial EF of the ADO. Net object data model. The entityobject of the object model is coupled with the objectcontext, which is not suitable for Stratified use. Ado. NET Self-Tracking Entity Generator separates and generates poco-based selftrackingenityobject model and objectcontext
(This method cannot load the associated navigation attributes even if delayed loading is set. It must be manually loaded during use.) ADO. Net dbcontext generator generates a pure poco model and a lightweight dbcontext separately. Compared with objectcontext, dbcontext is more concise and POCO can be fully utilized. That's why I chose ADO. net dbcontext generator. Let's look at the Division mode of the EF framework: Database firstmodel firstcode first database first traditional table-driven creation of EDM, and then generate the model and data layer code through EDM. In addition to the entity model and self-tracking implementation model, the pure poco model and lightweight dbcontext model can also be generated. Model first, create an EDM model, and then generate the DDL database script and model and data layer code. In addition to the entity model and self-tracking implementation model, the pure poco model and lightweight dbcontext model can be generated. Code first manually creates a poco model, dbcontext on the data layer, and ing relationships. database. setinitializer is used to generate a database. This method is flexible, but the code works a lot. Although code first is flexible, it is impossible to manually write a large number of Poco classes and ing relationships. If you use other ORM tools to generate code
First requires the POCO class. Why do we need to use model first to generate code first? This article selects the model first method + generate code-based data through ADO. Net dbcontext generator.
Is the first method of code a bit confusing? However, this method is basically the same as nhib.pdf, and nhib.pdf has a wide range of project foundations. The model first method is mainly used to build models and EDM ing files. Ado. Net dbcontext generator generates poco models, dbcontext codes, and DDL database scripts based on EDM files. Because code
First, you need to implement the Code of Poco and dbcontext by yourself. If you do not use a tool to implement the Code, the amount of code will be large. It is impossible for a project to complete the demo just like writing a demo and using a few simple classes for demonstration. It is impossible to learn for demonstration and ultimately improve work efficiency. This is why I think EF is mature and used for projects. Next, we will simply go through this process: 1. First, create a project, class library ef. Model, EF. Dal, EF. Bll, and console ef. demo. Create an empty EDM model in the ef. Dal class library
(Why is it in EF. dal creates EDM instead of EF. create in the model, as described later). Open the empty EDM model. We will build several object objects and map the relationships between objects. The EDM view is as follows:
Right-click Properties and select generate Database Based on Model-> Generate demodb. edmx. SQL script-> right-click the script and execute SQL
Generate to database 2. Add the code generation to complete our object design, right-click the EMD Attribute-> Add the code generation item...-> select ADO. Net dbcontext
Generator generator. At this time, edmx becomes an empty template. After the property generation code policy is disabled, two TT files, one demodb, are automatically generated. context. TT (dbcontext), a demodb. TT
(POCO)
Demodb. edmx and demo. TT
Copy the two files to EF. Model and delete the files in EF. Dal. Because demodb. edmx and demo. TT
The two files are created in EF. Dal, so they are moved to EF. Model and Their namespace is EF. Dal. Don't worry. Open it in EF. model.
Demodb. edmx and demo. tt template files. After you click Save, the template automatically changes the namespace to EF. model. Note that in EF. Dal
Do not open and save the demodb. Context. tt template; otherwise, the dbcontext code will be lost. This completes the separation of model and Dal code. (Dbcontext is the content of ef4.1. In addition, the Extension Manager in the VS solution tool can directly download the latest vs extension plug-in.
Directly add references to the console of Package Manager.) if the object is modified, you only need to save the EDM template to update the objects in demodb. TT in time. The Dal layer basically does not need to be modified. 3. EF. Dal create the irepository interface (IOC injection) using system; using system. Collections. Generic; using system. LINQ; using
System. text; namespace EF. dal {public interface irepositoryt> where T: Class, new () t create (); t Update (T entity); t insert (T entity); void Delete (T entity ); t find (Params object [] keyvalues); listt> findall (); repositorybase abstract base class to implement using system; using system. collections. generic; using system. LINQ; using
System. Text; using system. Data; using system. Data. entity; using EF. Dal; namespace
Ef. Dal {public abstract class repositorybaset>: irepositoryt> where T
: Class, new () Public dbcontext context; // provides the IOC Injection Interface public repositorybase (demodbentities context) {This. context = context;} // public repositorybase () {This. context = new demodbentities () ;}# region irepositoryt> member public t create () return context. sett> (). create (); Public t Update (T entity) // run the validation service // context. entry (entity ). getvalidationresult (); If
(Context. Entry (Entity). State = entitystate. modified)
Context. savechanges (); Return entity; Public t insert (T entity) context. sett> (). add (entity); context. savechanges (); Return entity; Public void Delete (T entity) context. sett> (). remove (entity); context. savechanges (); Public t find (Params object [] keyvalues) return context. sett> (). find (keyvalues);} public listt> findall () return context. sett> (). tolist (); # endregion} iblogcategoryrepository interface (IOC injection) using system; using system. collections. generic; using system. LINQ; using
System. Text; using EF. Model; namespace ef. Dal {public interface
Iblogcategoryrepository: irepositoryblogcategory> blogarticlerepository implements using system; using system. Collections. Generic; using system. LINQ; using
System. Text; using EF. Model; namespace ef. Dal {public class
Blogarticlerepository: repositorybaseblogarticle>, iblogarticlerepository: Check that the code for the next two specific data operation classes is extremely simple. This is the advantage of generics after ef4.0, which can make the code as concise as possible. 4. EF. BLL layer simple implementation of business blogcategoryservice
Associate a table (add a blogcategory category and add a blogarticle article under this category) using system; using system. Collections. Generic; using system. LINQ; using
System. Text; using EF. Dal; using EF. Model; namespace ef. BLL {public class blogcategoryservice {irepositoryblogcategory> repositorycategory; irepositoryblogarticle> repositoryarticle; Public
Blogcategoryservice (irepositoryblogcategory> repositorycategory, irepositoryblogarticle>
Repositoryarticle) {This. repositorycategory = repositorycategory; this. repositoryarticle = repositoryarticle; Public blogcategoryservice () {This. repositorycategory = new blogcategoryrepository (); this. repositoryarticle = new blogarticlerepository ();} public blogcategory createblogcategory () return repositorycategory. create ();} public blogarticle createblogarticle () return repositoryarticle. create (); Public blogcategory insert (blogcategory entity) return repositorycategory. insert (entity); Public blogcategory Update (blogcategory entity) return repositorycategory. update (entity); Public void Delete (blogcategory entity ){
Repositorycategory. delete (entity); 5. EF. model Test navigation attribute Association operation (insert records to two tables at the same time) using system; using system. collections. generic; using system. LINQ; using
System. text; using EF. model; using EF. bll; namespace EF. demo {class program {static void main (string [] ARGs) {blogcategoryservice service = new blogcategoryservice (); // create a blog category blogcategory Cate = service. createblogcategory (); Cate. catename = EF category label; // create a blog post blogarticle arti = service. createblogarticle (); Arti. title = EF evolution;
Arti. content = EF test content; // Add the blog post to the blog category Cate. blogarticle. add (ARTI); // Update Service. insert (Cate); console. readline () ;}} 6. result
Use model first + ADO. Net dbcontext generator to implement code
First-way business (edmx is injected through dbcontext construction) to achieve the effect of hibernate. Edmx is equivalent to hibernate
Object Model XML ing file, Poco is equivalent to hibernate Object Model (Virtual Implementation of associated navigation loading), dbcontext is constructed through generics
Irepository data operation class. According to relevant tests, the test efficiency of ef ado. NET is higher than that of hibernate.
Around 30%. I don't know if it's true-_-|. In addition, dbcontext
It can be converted to objectcontext and decompiled with refletor. We can see that the implementation code is implemented through an intermediate internalcontext: objectcontext context = (iobjectcontextadapter)
Dbcontext). objectcontext; if you do not want to directly load navigation attribute data, you can disable delayed loading in the dbcontext constructor. ///// This code is generated based on the template. //// Manually changing this file may cause abnormal behavior in the application. // If the code is re-generated, the manual changes to the file will be overwritten. /// Namespace EF. dal {using system; using system. data. entity; using system. data. entity. infrastructure; using EF. model; public partial class demodbentities: dbcontext public demodbentities (): Base (name = demodbentities) {// disable delayed loading this. configuration. lazyloadingenabled = false; // disable the proxy this. configuration. proxycreationenabled = false; protected override void onmodelcreating (dbmodelbuilder
Modelbuilder) throw new unintentionalcodefirstexception (); Public dbsetblogarticle> blogarticle {Get; set;} public dbsetblogcategoryrepository> blogcategory {Get; set;
} Public dbsetblogcomment> blogcomment {Get; set;} public dbsetblogdigg> blogdigg {Get; set;} public dbsetblogmaster> blogmaster {Get; set;} public dbsetblogtag> blogtag {Get; set;} EF provides a powerful query framework. If you have time to write more articles to explore custom queries, you don't have to worry about it. You can practice it in the project. If the datetime field of the table design cannot be blank, an error occurs when EF executes savechanges. We recommend that you use the datetime2 type (Versions later than sql2008)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.