ADO.NET Entity Framework – Overview
The ADO.NET Entity Framework enables developers to create data access applications by programming against a conceptual application model instead of programming directly against a relational storage schema. The goal is to decrease the amount of code and maintenance required for data-oriented applications. Entity Framework applications provide the following benefits:
· Applications can work in terms of a more application-centric conceptual model, including types with inheritance, complex members, and relationships.
· Applications are freed from hard-coded dependencies on a particular data engine or storage schema.
· Mappings between the conceptual model and the storage-specific schema can change without changing the application code.
· Developers can work with a consistent application object model that can be mapped to various storage schemas, possibly implemented in different database management systems.
· Multiple conceptual models can be mapped to a single storage schema.
· Language-integrated query (LINQ) support provides compile-time syntax validation for queries against a conceptual model.
Getting Started (Entity Framework)
The Entity Framework supports the Entity Data Model (EDM) for defining data at the conceptual level. When using the ADO.NET Entity Data Model Designer, conceptual model, storage model, and mapping information is contained in an .edmx file. The Entity Framework also enables developers to program directly against the data types defined at the conceptual level as common language runtime (CLR) objects. The Entity Framework provides tools to generate an .edmx file and the related CLR objects based on an existing database. This reduces much of the data access code that used to be required to create object-based data application and services, and makes it faster to create object-oriented data applications and services from an existing database. The tools also allow you to build a conceptual model first, and then automatically generate related CLR objects and a supporting database.
Entity Framework applications and services are based on model and mapping information that is expressed in three XML-based languages:
· Conceptual schema definition language (CSDL)
· Store schema definition language (SSDL)
· Mapping specification language (MSL)
CSDL represents application data as a set of entities and relationships in a conceptual model, and it is an implementation of Entity Data Model. A storage model is expressed in SSDL and represents the schema of the data store. The mapping between the two models is expressed in MSL.
The CSDL, SSDL, and MSL content for an application can be automatically generated by the ADO.NET Entity Data Model Tools. The Entity Data Model Wizard generates model and mapping information as well as data classes from an existing database. The Entity Data Model Designer (Entity Designer) can then be used to graphically modify model and mapping information.
For our example, we refer to Updategram scenario, which consist of following tables:
Refer following steps for generating model and mapping information using Entity Data Model Wizard.
1. Create a Visual C# Class Library project and name it as Titles.Samples.Data.
2. After project is added, Add New Item and select ADO.NET Entity Data Model. Name it as Titles.Model.asmx.
3. In the appearing window, select ‘Generate from database’ and click on the ‘Next’ button. It will open ‘Choose Your Data Connection’ page which allows configuring destination database connection.
4. Select ‘New Connection’ to configure desired connection settings. For our example, we consider Server Name as ‘localhost’, Use Windows Authentication and Database as ‘Staging’. Test the connection and click on the ‘OK’ button.
5. In ‘Choose Your Data Connection’ page, click on the ‘Next’ button to open ‘Choose Your Database Objects’ page. This page allows us to select the desired tables (mentioned in above list) to generate Entity Model and apply corresponding mappings between the selected tables. Also, change Model Namespace to ‘Titles.Sample.Data’, and click on the ‘Finish’ button.
6. Now, the Entity Model ‘Titles.Model.edmx’ is generated with selected tables and their relationships. Save the project.
7. Go to ‘Solution Explorer’, select ‘Titles.Model.edmx’ file and view its properties. In ‘Properties’ pane, empty ‘Custom Tool’ property. It will remove ‘Titles.Model.Designer.cs’ file from the project.
[Note: Our solution targets POCO Entity Classes, and hence we ignore the code generated by ‘Custom Tool’ mentioned in ‘Titles.Model.edmx’ file properties. In the next section, we use ‘ADO.NET POCO Entity Generator’ to generate the required POCO entity classes corresponding to each table in the model.]
Generating POCO Entities using ‘ADO.NET POCO Entity Generator’
POCO stands for Plain-Old CLR Objects. POCO support in Entity Framework 4.0 means that these EntityObject - based types can be replaced with much simpler classes. POCO entity types are not required to inherit from any particular class and do not need attribute to map to the homologous elements in the model. Instead, types and properties in the objects and in the model are associated at runtime simply based on their names.
Adding the POCO template
The POCO Template can provide a good jumpstart by generating POCO classes that correspond to the model instead of the default EntityObject classes.
1. In order to do this, you can right-click on an empty area of the “Titles.Model.edmx” canvas and select ‘Add Code Generation Item…’
2. This will bring up the Add New Item dialog, in which you can choose which Template you wish to use. The POCO Template can normally be found under the Visual C# category.
3. On this screen select “ADO.NET POCO Entity Generator” and type “Titles.tt” as the name of the new item. Then click on the ‘Add’ button.
Understanding how the POCO Template works
When you choose the POCO Template two T4 template files are added to your project. In this case one is called “Titles.Context.tt” and the other is called “Titles.tt”. T4 stands for Text Template Transformation Toolkit, and is a template engine that ships with Visual Studio. The Entity Framework POCO Template leverages T4 to allow you to customize code generation.
Once you have added the POCO template, your project will look like this:
The “Titles.tt” file is responsible for generating a file for each EntityType and ComplexType in the “Titles.Model.edmx” model. “Titles.tt” also generates a file called “Titles.cs”, which contains a FixupCollection<T> class used by the POCO classes to keep the opposite ends of a relationships in sync.
The second template (“Titles.Context.tt”) produces a strongly typed ObjectContext for the “Titles.Model.edmx” model. You use this strongly typed ObjectContext to interact with your database.
Note that each time you edit and save any T4 template the dependent files are regenerated, so you shouldn’t edit the generated files directly, or your changes will be lost. If you wish to modify the generated code, you can modify one or both of these templates.
The primary goal of the POCO template is to produce persistence ignorant entity classes.
However, the strongly typed ObjectContext derives from ObjectContext, which is an Entity Framework class. So this template must live in a project with a reference to the Entity Framework.
By splitting the template into two, one part that generates the Entity Types and Complex Types and one that generates a strongly typed context, it makes it possible not only to have Entities and ComplexType that are persistence ignorant but further to put those classes in an assembly / project that has no persistence aware code in it at all.
Moving entity types to a separate project
1. To continue, add a new Class Library project to the solution called Entities. You can remove the class1.cs file created by default in the new project.
2. Now, in the “Titles.Sample.Data” project, add a project reference to the “Titles.Sample.Entity” Project:
3. Next, move the “Titles.tt” file into the Entities project. To do that, you can simply drag & drop the file into the Entities project in the Solution Explorer window, while you hold the Shift key at the same time.
Fix the link to “Titles.Model.edmx”
The POCO Template’s template files need to be able to read metadata from the EDM model in order to generate the right code. Since we have moved the template, the relative location of the Model has changed; therefore we need to fix the template so its link back to the model is correct again. To do this you can modify a line close to the top of the template from:
string inputFile = @ “Titles.Model.edmx” ;
string inputFile = @ “..\Titles.Sample.Data\Titles.Model.edmx”;
This is simply a relative path from the template’s new location to the Titles.Model.edmx file in the other project.
Replacing ICollection<T> to List<T>
The POCO Template generates entity classes with Navigation Properties which are used to maintain foreign-key relationships. ICollection<T> is used to hold the related entity type. Our approach is to represent entity classes as XSD (generated using XSD.exe), to enable mapping using BizTalk Mapper. Since, ICollection<T> doesn’t support serialization, we replace ICollection<T> with List<T> to maintain this relationship. To do this you can modify “Titles.tt” to reflect the changes in all entity classes. Refer below code snippet for the corresponding changes.
Once you’ve done this, Save the template, and this will regenerate the POCO entity classes. You can check that the contents of the file “Titles.cs” under “Titles.tt” has the right contents to verify that the path entered. Also, notice the “Titles.Sample.Entity” project has no reference to the System.Data.Entity (aka the Entity Framework), and is completely persistence ignorant.
Generating XSD representing POCO Entities using XSD.exe
After successfully compiling ‘Titles.Sample.Entity’ project, using XSD.exe generate the Schema (XSD) file representing the entities in ‘Titles.Sample.Entity’ assembly.
1. Open Command Prompt by typing ‘CMD’ in RUN Command.
2. Navigate to ‘Titles.Samples.Entity’ project folder, and run XSD tool by providing the path of ‘Titles.Samples.Entity.dll’. Refer below screenshot:
3. Add the schema files (.xsd) generated as a part of your BizTalk schemas project. The schema generated would look like below.
4. All the schema nodes are separated as individual root nodes. Since our transformations require mapping input data to all these nodes, we group them under a single root node named ‘Titles’.
Now this schema could be used for transforming Titles Canonical message to Titles Entities message, which in runtime will be de-serialized into individual entities and saved into database. We will cover this in next section.
The credit of this approach goes to David Bastow (http://www.linkedin.com/pub/david-bastow/7/60/b7b).
The credit of this approach's execution goes to Sathish Krishnan (http://www.linkedin.com/in/satykrish).