Go The Entity framework to grasp the global

Source: Internet
Author: User
Tags management studio sql server management sql server management studio

Learning the Entity Framework technology during the review of excellent articles, for the sake of convenient access later, reproduced to the blog, can read the original: http://blog.csdn.net/bitfan/article/details/12887007

The purpose of this article is to make an overall impression of the technology and understand its rationale before delving into the technology.

I. Understanding the EF data Model

EF is essentially an ORM framework that needs to map objects to tables in the underlying database, and for this reason, it uses three models to describe this mapping relationship.

(1) The conceptual model (conceptual model): The main embodiment is a set of classes that can be used directly by the application. These classes are also classes that we use directly in our programs, often referred to as "entities"

(2) storage model (Storage models): A group of classes that correspond directly to the underlying data storage media, such as a database system.

(3) concept-storage model mapping (Conceptual-storage Mapping)that solves the problem of how classes in the conceptual model correspond to classes in the storage model.

The types in (2) and (3) are used internally by EF and are usually not accessible in actual development.

All of these three models are centrally placed in an XML-named EDMX file.

VisualStudio provides a wizard to complete the mapping transformation between the existing database and the EF data model:

When this wizard finishes, EF successfully establishes the following correspondence between the database and the objects used in the program:

world of relational databases

the world of database Applications

Database

DbContext class

Table

DbContext dbset< entity class name;

Association between tables

entity classes

fields in table

Public properties of entity class

Table single record

Objects of a single entity class

View

DbContext dbset< View name >

Stored procedure

DbContext public methods

You can see the conceptual model and storage model of the EF data model in the Model navigation panel of visual Studio, and if you open the. edmx file directly in XML format, you can see all three big data models of "authentic".

The EF wizards provided by Visual Studio not only generate these three big data models, It also uses the T4 code template (which has a. tt file name extension) to generate the corresponding entity class directly, and a subclass derived from DbContext, which contains database elements such as all entity collection properties and imported stored procedures. This dbcontext subclass is the core type we use for the EF development program.

Double-clicking the "edmx" file in Solution Explorer opens the EF designer, which is a powerful tool that can be used for almost any work that adjusts the data mapping relationship.

If you are developing based on database first or model first, then the EF Designer is something you have to deal with every day. It is simple to do: Right-click the designer and select the command from the pop-up menu .

There's a lot of information about the various commands and how to use the EF designer, and there's no nonsense here.

Ii. basic ways to access a database using EF

There are four ways in which you can access the database in EF:

Entity SQL is a query language designed specifically for EF, very similar to common relational database query language SQL, but it returns data that is defined in the EF "conceptual model" rather than the "true look" of the data in the database.

LINQ to Entities can be seen as a "variant" of LINQ to Objects, querying the EF Data Model through LINQ. It uses object services at the bottom to complete its functionality. Object Services is a set of classes used to query the Entity Data model, which can convert these query results to strongly typed CLR objects.

Whether you use Entity SQL or LINQ to Entities, you end up relying on the "entity Client" to do its job.

The Entity client contains a set of classes, such as EntityConnection, EntityDataReader, and so on, very similar to the ADO model, and its functions are similar. The Entity client forwards the CRUD request for data to the ADO. Provider component, which sends the relevant SQL commands directly to the database.

In real-world development, data query work is done using LINQ to Entities and a set of extension methods for ienumerable<t>/iqueryable<t>, and almost no one directly uses Entity SQL and Entity Client.

Shows the internal processing flow of EF queries during the run of several applications:

As you can see, data queries that use EF from emit to true execution are going through two "command tree" transformations, and reading from the database is also going to go through the dbdatareader-->entitydatareader--> Conversion of ienmerable<t>. While EF uses caching, precompilation, and other means to improve performance, However, compared with ADO, because of the intermediate processing links more, the entire query processing process involved in more objects, so the overall performance is generally inferior to ADO, and will occupy more memory, which we are to enjoy the convenience of EF at the same time, the need to pay the price.

Also, since all queries are ultimately converted to SQL commands, some of the extension methods available to LINQ to objects, such as last (), will not work in EF because EF does not know how to translate them into SQL commands supported by the underlying database.

PK for three or three development models

EF supports three development models:

Code First, Database first, and model first.

It is a tangled question that the pattern should be used.

Mode one: Code first

EF's code first is a bit of a magic color for people who are on the initial contact. Let's take a look at the following.

Create two classes: Book and Bookreview (review). A book can have many book reviews, so they are a one-to-many relationship:

 Public classBook { Public Virtual intId {Get;Set;}  Public Virtual stringName {Get;Set; }  Public VirtualList<bookreview> Reviews {Get;Set; } }    Public classBookreview { Public intid{Get;Set;}  Public intBookId {Get;Set; }  Public Virtual stringContent {Get;Set; }  Public VirtualBook Assoicationwithbook {Get;Set; } }

OK, now create a subclass derived from DbContext:

 Public class Bookdb:dbcontext    {       publicgetset;}         Public Get Set ; }}

You can now write a few lines of code in your program to extract data from the database:

Static void Main (string[] args)       {           using (varnew  bookdb ())           {                Console.WriteLine (" there are {0} books in the database ", context.) Books.count ());           }       }

To run, if you have SQLExpress installed on your computer, either in the Application folder, or by opening SQL Server Management Studio (SSME) to view native SQL Server, you will find that the database has been created. The tables and tables associated with them also help you to complete the following:

It seems that I did nothing, everything is OK, magic Ah!

Now modify the book class and add a authors property to it, representing the

 Public classBook { Public Virtual intId {Get;Set;}  Public Virtual stringName {Get;Set; }  Public Virtual stringAuthors {Get;Set; }  Public VirtualList<bookreview> Reviews {Get;Set; }}

With a good first impression, you must think that as soon as you run the program again, the underlying database will automatically update, however, EF will give you blow to wake you up:

Obviously, because you modify the entity class, the database structure also needs to be modified, the more depressing is that you can not open the creation of the database directly modified, and need to use a function called "Database Migration", in two ways (automatic migration and manual migration) one of the completed.

Take automatic migration as an example:

First open the package Manager Console from the Tools menu, and then type:

Enable-migrations–enableautomaticmigrations

The above command adds a migrations folder to the project, which will have a configuration class that you need to add "automaticmigrationdatalossallowed = True" in its constructor for convenience. , let it automatically rebuild the database regardless of possible data loss:

Internal Sealed class Configuration:D bmigrationsconfiguration<efcodefirst.bookdb>    {       public  Configuration ()       {           true;            true ;       } ...}

OK, now run the update-database command to update the database:

Run the program again and now everything OK.

Each time you change an entity class later, you must manually update the database by running the update-database command.

Manual migration is basically the same as automatic migration, except that it records each update, allowing the database to be rolled back to an older version.

The automatic method is more suitable for single-person writing applications. The manual method can control the update of the database structure, which is more suitable for team development.

The advantages of Code first mode.

From the above introduction, you can see that code First has outstanding advantages.

(1) is code cleaner, adding custom logic is easy.

This is the biggest benefit of using code first

Especially in desktop applications such as WPF, which can maintain long connections, you can have entity classes implement the Inotifyproperty interface and put them in ObservableCollection as a bound data source for the UI interface. can take advantage of WPF's data binding and EF's automatic maintenance of entity state features, drastically reducing code.

(2) easy to implement inheritance

Code first is very handy for implementing inheritance, and if you have a large number of inheritance in the data entity, it is convenient to use code first, but it is important to note that code first uses the "tph:table Per Hierarchy" mode by default when generating database tables. Plug the parent subclass into the same table and add a discriminator field to the table that indicates the specific type to which this record belongs.

The following is a database table generated by Codefirst for the two parent/child classes that have an inheritance relationship, and you can see that the discriminator field holds the specific data type.

Some friends asked if I could get rid of the discriminator field name, unfortunately, I didn't find a way to modify it.

Obviously, this implementation strategy adopted by Code first violates the relational database design paradigm, which is not easy for large projects to maintain data consistency.

Another way to implement inheritance is tpt (table Pertype), regardless of the subclass parent class, one table per type.

For example, there are three classes, instruct and student derive from person, and if you adopt a TPT strategy, EF generates three tables and creates the following associations:

For TPH, handwritten SQL code is easy and performance is high, but for TPT,EF generates a lot of inner Joint when generating SQL commands, performance is low, and for the data stored in this way, handwritten SQL code is more troublesome.

Database first and model first are TPH by default.

My advice: unless the two entities are really is_a relationships, and you need to use polymorphism in the middle tier, use inheritance as little as possible in the data Access Layer (DAL), and don't trouble yourself .

(3) Some developers have also provided EF with a entityframework Power tools, which enhances the functionality of code first, such as the ability to directly reverse-Generate entity class code from an existing database, which can then be modified for code The first way of development saves a lot of coding work. It also generates a read-only view of the data model for the written entity class code, showing the association between entity classes graphically.

Problems with Code first

Codefirst trying to "fix everything with code", the problem is the following points:

(1) When model changes, it is often necessary to write code to implement database changes, far less than directly using the tools provided by the database to modify the database security and intuitive, at least the possibility of loss of data is much less.

(2) When there is a complex association between data entities, it is cumbersome to use the fluent API to manually write many code-defining associations between classes.

(3) Some fine-tuning of database tables and associated properties (such as changing field names, modifying field length limits, etc.) can be easily implemented using database design tools, but code first can only be done through the codes, and the data migration features of EF must be used, which is a hassle and error-prone process.

In short, the Code first application scenario is: rapid development, rapid iteration .

Mode two: Database first

This is the feature that EF has supported since 1.0, with the idea of designing and building a database, and then using Visual Studio's wizards to create the EF data model and generate the entity class code.

This is the most mature and stable way, its designer is quite perfect, basically can meet the various needs in the actual development.

I personally think this is the most appropriate way to develop a formal project.

There are, of course, some problems with databasefirst, mainly when it comes to customization. Like what:

(1) To add some custom logic to an entity class or generated DbContext subclass, you apply a partial class, because each time the data model is updated, the code is overwritten and rewritten by the designer.

(2) The generated entity class does not include any data Annotation (so-called "data Annotation" is attached to the entity class code such as [Required], etc.), so it needs to be converted to another class, in order to conveniently in such as ASP. The use of projects such as MVC (such as the View Model (ViewModel) class in an ASP. NET MVC project often requires data Annotation to work with the jquery validation plug-in to generate validation code on the Web page).

(3) By default, the entity class and the edmx file are placed in the same project, want to separate the entity classes into separate projects, need to complete some additional configuration work (mainly to move the T4 template file to another project, which requires the appropriate modification of the code in the T4 template file to ensure that the file path reference is correct).

Mode three: Model first

This pattern is to create the entities and their associations in the visual designer first, and then the designer generates the SQL commands and saves them in a SQL file to complete the creation and modification of the database by executing the SQL file .

I personally feel:

This approach is most suitable for newly developed projects , starting from the system analysis, gradually analyze the establishment and refinement of the domain model, then you can immediately create a database, if the model has been modified, regenerate a SQL file, and then execute once, is very suitable for the new project Ooad stage needs.

When entering the OOP stage, because the database has already existed, it can easily switch to the database first mode, the whole process is smooth and natural.

Three modes of PK results:

CodeFirst: for small or experimental projects, especially as I often lecture, teaching examples using Code first development is more appropriate, when the program runs the database automatically generated, more convenient.

DBFirst: The most mature, is the preferred way of formal projects, because the developers themselves (rather than through a bunch of "less reliable" code) directly manipulate the database, the entire process is highly controllable, can ensure data security, and implement the " data is more important than code " 's philosophy.

ModelFirst: When you start a new project that has no DB, no code, it's good, it's a good tool for ooad, and you can even generate SQL code that creates a variety of different types of databases, like MySQL, when needed!

Go The Entity framework to grasp the global

Related Article

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.