Many developers may be unfamiliar with EF, as it was released in between VS2008 and VS2010, and others may have heard bad things about it (not all of which are true). Let's take a quick look at how to work with EF before looking at the new features in EF4.
All EF applications contain an entity data model (EDM) that describes the objects in the underlying data source. The EDM can be further divided into three layers:
Conceptual model (the view your users see)
Storage model (how data is actually stored)
Mapping model (links the conceptual and storage models)
EDMs are stored as XML and are composed of three main sections (which link to the three conceptual layers already described):
CSDL (Conceptual Schema Definition Language)
SSDL (Store Schema Definition Language)
MSL (Mapping Specification Language)
It is important to understand the format of the EDM file. EF contains good GUI support, but for more advanced customizations, it is necessary to modify the XML file directly. The exact format of your EDM file is also dependent on how it is generated (described next).
If you generate your model using the wizard in Visual Studio, the EDM will be held in one file with the extension .edmx with the conceptual, storage, and mapping sections split under the following nodes:
edmx:StorageModels
edmx:ConceptualModels
edmx:Mappings
If, however, you generate your model using EDMGen.exe (discussed next), then the model will be split into three separate files: .SSDL, .CSDL, and .MSL.
You can create an EDM in three different ways:
By using the EDMGen command-line tool
By using the ADO.NET data model wizard in Visual Studio
By creating the model in Visual Studio and then having Visual Studio generate your database structure from this model (new to EF4)
EdmGen.exe is a command-line tool primarily used for generating an EDM, but it also performs a number of other tasks, such as verification of models and splitting generated files. You may want to utilize EdmGen as part of your application's build process.
The easiest way to create an EDM is by using the ADO.NET Data Model wizard in Visual Studio.
Open up Visual Studio.
Create a new C# console application and call it Chapter8.HelloEF.
Right-click the project and select Add New Item.
Select ADO.NET Entity Data Model, and name it Chapter8Model.edmx (Figure 8-1).
Click Add.
The Choose Model Contents screen will now appear (Figure 8-2). Select the "Generate from database" option.
Click Next.
Visual Studio will now ask you for a connection (Figure 8-3). If you haven't done this already, create a new connection to the example database. Note that my database is called Book, so EF will prefix many settings with the name of the database (you may wish to change this).
You now need to select the items in the database that you want EF to create entities for. Expand the Tables node and select the following tables (Figure 8-4):
Film
FilmShowing
Order
OrderItem
NOTE
The wizard also allows you to create entities for views and stored procedures.
Ensure that you have checked "Pluralize or singularize generate object names" and "Include foreign key columns in the model" (these are new options in EF—for more information, please refer to the following "Pluralization" section).
Set the model namespace as BookModel.
Click Finish. EF will then generate entities for the classes you have created, and you will be taken to the design view of the generated EF model (Figure 8-5).
Notice how relationships between the entities have been automatically created. This is because our database contained a number of constraints and relationships that were automatically imported into our model. You can also create relationships yourself in the design view.
When your EF model contains many entities, the designer window can get pretty crowded. You can zoom in and out of the model view by clicking the magnifying icons in the corner of the scrollbars or by right-clicking and selecting the zoom level.
If you select one of the entities and then view the Mapping Details window, you will see how the individual properties on the entity are mapped to the underlying database fields (Figure 8-6).
Now select one of the individual entity properties, and Visual Studio will display information in the Properties window, such as the type of field, length, and so on. Notice how you can also change the name of the field and the getter and setter properties' access levels (Figure 8-7).
When you make changes to your database, you will also need to update your EDM. To update the model, simply right-click the design surface and select Update Model from Database. Visual Studio will then bring up a dialog box allowing you to add additional tables and fields (Figure 8-8). Note that this release of EF improves the resolution of conflicts/orphaned model elements in the model browser window:
EF allows you to query objects in a number of different ways:
Using L2E
Using ObjectQuery methods
Using Entity SQL
Whichever query method you use, the query gets transformed into the same query tree structure that is then processed by your model's data source provider.
L2E is probably the easiest query method. L2E gives you rich query functionality and IntelliSense support, and it is very easy to use. Let's write some code to iterate through our Orders and OrderItem tables displaying information about these entries.
Modify the Main() method to the following (note that your entity set will, by default, be prefixed with the same name as the database—in the following example, mine is Book).
static void Main(string[] args) { BookEntities ctx = new BookEntities(); var query = from o in ctx.Orders select o; foreach (Order order in query) { Console.WriteLine("Order: " + order.OrderID.ToString() + " " + order.Firstname + " " + order.Lastname); order.OrderItems.Load(); foreach(OrderItem orderItem in order.OrderItems) { Console.WriteLine("Adult: " + orderItem.QtyAdult.ToString() + " Child:" + orderItem.QtyChild.ToString()); } Console.WriteLine(""); } Console.ReadKey(); }
The results are shown in Figure 8-9.
You can also query EF objects with the ObjectQuery class. Let's take a look at this now.
Add the following using directive to Program.cs:
using System.Data.Objects;
Replace the LINQ query with the following line of code (note that it refers to the current entity, which in this case is Order):
ObjectQuery<Order> query = ctx.Orders.OrderBy("it.OrderID");
Entity SQL is similar to T-SQL (but has its own EF-specific features and intricacies); the following is an example Entity SQL query:
string queryString = @"SELECT VALUE o FROM BookEntities.Orders AS o"; ObjectQuery<Order> query = new ObjectQuery<Order>(queryString, ctx, MergeOption.NoTracking);
We have barely touched what Entity SQL is capable of, so for more information (on anything EF-related), please refer to Julia Lerman's book Programming Entity Framework (O'Reilly, 2009).
3.147.81.186