8.4. EF 101

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.

8.4.1. Entity Data Model

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.

8.4.2. Creating an Entity Data Model

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)

8.4.2.1. EdmGen.exe

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.

8.4.2.2. Creating an Entity Data Model in Visual Studio

The easiest way to create an EDM is by using the ADO.NET Data Model wizard in Visual Studio.

  1. Open up Visual Studio.

  2. Create a new C# console application and call it Chapter8.HelloEF.

  3. Right-click the project and select Add New Item.

  4. Select ADO.NET Entity Data Model, and name it Chapter8Model.edmx (Figure 8-1).

  5. Click Add.

  6. The Choose Model Contents screen will now appear (Figure 8-2). Select the "Generate from database" option.

    Figure 8.1. Adding an ADO.NET EDM to your project

    Figure 8.2. Generate from database
  7. Click Next.

  8. 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).

  9. Click Next.

    Figure 8.3. Connection string properties
  10. 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.

    Figure 8.4. Selecting items to generate EF classes for
  11. 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).

  12. Set the model namespace as BookModel.

  13. 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).

    Figure 8.5. Design view of EF model

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.

8.4.3. Navigating the EF model

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.

8.4.3.1. Viewing How Entities Are Mapped

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).

Figure 8.6. EF Mapping window

Figure 8.7. Viewing the properties of Film.Description

8.4.3.2. What Happens If My Database Structure Changes?

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:

Figure 8.8. Update Model from Database

8.4.4. Querying Data

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.

8.4.4.1. LINQ to Entities

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.

  1. Open Program.cs.

  2. 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.

Figure 8.9. Output of L2E query

8.4.4.2. ObjectQuery

You can also query EF objects with the ObjectQuery class. Let's take a look at this now.

  1. Add the following using directive to Program.cs:

    using System.Data.Objects;

  2. 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");

8.4.4.3. Entity SQL

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).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.81.186