Category Archives: Data Model

Code-First Entity Framework’s Fluent API

By Tim Daniels
This is a follow-up to my post on the Code-First Development Workflow. In that post I described how the Code-First workflow automatically generated an object model and a SQL Server database, by implementing the concept of convention over configuration. With this approach, Code-First assumes that the POCO classes defined in the Entities class library, follow the conventions of the schema that Entity Framework uses for a conceptual model. If this is the case, then Entity Framework is able to work out the details of what needs to be done, to form the object model and the relational database. However, if the conventions established in the POCO classes do not produce the desired result, you still have the ability to add configurations to your classes. As we look more closely at this approach, you will see that sometimes the best solution, is a compromise between two opposing techniques and technologies.

When I defined the domain entities for the Action Manager app, I created a one-to-many relationship between the customer object and the project object. In other words, a customer can have one-to-many projects. Here is the code where this is accomplished.

In the customer class, there is a virtual property called Projects, which is defined as a generic list of Project objects. This is known as a navigation property. The project class also has a navigation property of type customer. In this case, the navigation properties establish the convention that a customer can have one to many projects. With this bit of information, Entity Framework created the Customers table and the Projects table in the SQL Server database as illustrated here;

Fluent API Customers table and Projects table

Fluent API Cutomers table and Projects table


As you can see from the code snippet above, I chose not to clutter up the project class with a property for customer ID. However, this caused Entity Framework to create a foreign key relationship between projects and customers that allows the foreign key to be null. Obviously, this was not my intention.

With the code-first fluent API, I can configure the contextual model to generate the foreign key relationship between project and customer ID as not nullable. Here is the code where this is accomplished.

The DbContext class has an overridable method called OnModelCreating. This is where I can tweak the conventions of the entity classes, with specific configurations, to produce the desired result. In this case, the HasRequired method of the modelBuilder class, configures the Customer property of the Project entity, to be required for input. This configuration causes the foreign key relationship between project and customer ID to be defined as not nullable, as illustrated here.

Fluent API Configuration of Customers table and Projects table

Fluent API Configuration of Customers table and Projects table


Here is an outstanding article by Julie Lerman on Code First Relationships Fluent API. Julie covers this subject in more detail with several different examples of configuration through the fluent API.

Code-First Development Workflow

By Tim Daniels
Over the past few weeks I’ve continued using the code-first workflow. At this point, I’m ready to share what I’ve learned and what I’ve developed so far. The code-first workflow enabled me to use the convention over configuration approach in the design and development of a solution. With this approach, I found myself focusing, almost exclusively, on the application of a solution to a business problem. Some thought and effort was given to architecture and application structure, but I did’nt concern myself with database design, or object model design, other than verifying that what was generated by the Entity Framework matched my requirements and expectations. The result was a solution, and code, that is very simple and concise. A complete, normalized relational database, and a complete object model were automatically generated by the Entity Framework.

Here is a brief description of the solution I’ve been developing. I call the application “Action Manager”. It’s a basic project management application written in C#.NET. The application will record and track the number of hours worked on a specific task, by a specific person, on a specific project, for a specific customer. The data is stored in a SQL Server database. For development purposes, I’m using SQL Server 2012, the express edition. The entire application is build on the .NET Framework 4.0.

In designing and developing an application, I first get a thorough understanding of the business domain the application will operate in. Understanding a business domain requires identification, and definition of the entities existing in the domain, and how they interact with each other. These entities are then abstracted into individual object-oriented classes in code. Here is a list of the entities currently identified and defined in the project management domain;

  • Customers
  • Projects
  • People (who work on the projects)
  • Titles (job titles)
  • Tasks
  • Rates
  • Timesheets
  • Timesheet entries

Following are the C# classes representing each of the entities in the project management domain. These classes are completely independent of a database source, the object relationship model (ORM), and any third-party attributes. They are also independent of any base class inheritance. This type of class is sometimes refered to as a plain old common language runtime object, or POCO class. I created one class library project called “Entities” to store these classes.

Convention over configuration
Examine each entity class closely. You will notice that the entities have properties which define relationships with other entities in the domain. For example, The customer class has a property called projects. This property is defined as a generic list of project objects. This establishes the conventional relationship between customers and projects, that is customers can have one to many projects. In the same way, the person class has a property called time sheets, establishing the convention that a person can submit one to many time sheets for work performed on a project. These properties are called navigation properties in the object model.

Notice also, that each class has an ID property defined with an object type of integer. The property is named after the class with a suffix of Id (e.g., CustomerId and PersonId). This naming convention is used by the entity framework to create a unique key column when generating tables in a database. This also facilitates the creation of primary key and foreign key relationships, in the object model and the database.

Entity Framework
The Entity Framework can use the conventional relationships established in these POCO classes to automatically generate an object model, and a relational database schema. The DbContext class is where this can be accomplished. The DbContext class is in the System.Data.Entity namespace. Let’s look at some code to see how this is done.

In the above code snippet I created a class called ProjectManagementContext which is derived from DbContext. I then added a property for each of the classes in my entity class library. The type of each property is DbSet. When developing with the Code First workflow you can define a derived DbContext that represents your session with the database and exposes a DbSet for each type in your model. The DbSet Class represents a typed entity set that is used to perform create, read, update and delete operations for each of the entities defined in the object model of the context.

Here is an illustration of the object model generated by the Entity Framework, based on the conventions defined in the POCO classes of the Entity class library. Notice the Navigation Properties, and how they form relationships between the objects in the model. For example, the one to many relationship between the customer object and the project object, is clearly illustrated here.

Object model generated by the Entity Framework in Code-First Workflow

Object model generated by the Entity Framework in Code-First Workflow


Here is an illustration of the database and database model generated by the Entity Framework.
Database generated by the Entity Framework in Code-First Workflow

Database generated by the Entity Framework in Code-First Workflow

In the near future I’ll be writing about the Entity Framework’s fluent API. I’ll also explore the implementation of the create, read, update and delete methods in the DbSet of entity class.

Here are several helpful links to help you get familiar with Entity Framework Development Workflows and the code-first workflow.

Code-First Development with Entity Framework 5.0

By Tim Daniels
As you know from previous posts, I prefer using an Object Relational Mapping (ORM) framework, as part of a domain driven approach to design and development of a business solution. The Microsoft ADO.NET Entity Framework is an Object Relational Mapping framework that enables developers to work with relational data as domain-specific objects, eliminating the need for most of the data access plumbing code that developers usually need to write. Developers can focus on their application-specific business logic rather than the data access fundamentals.

Recent development in the ADO.NET Entity Framework provide further support for two other software development techniques, which I find very appealing and effective, in design and development of new solutions.

  • Code-First Development Workflow
  • Convention over configuration

The code first approach offers several advantages to the application developer. It allows the developer to focus on domain specific entity classes and how these classes relate to each other in the business model. These classes are completely independent of a database source, the ORM and any third-party attributes. They are also independent of any base class inheritance. These classes are sometimes refered to as plain old common language runtime objects or POCO classes.

The entity classes form a set of conventions which the ADO.Net Entity Framework uses to automatically generate an object model and a SQL Server relational database.

Here is an example of two POCO entity classes. A time sheet object and a time sheet entry object. There is a one to many relationship between the time sheet object and the time sheet entry objects. This relationship is expressed by the TimeSheetEntries property of the TimeSheet class. This is known as a navigational property.

In the near future, I’ll be writing a series of posts on the Code-First development workflow, and then follow-up with a post on how code first ties into the convention over configuration development technique.

Here are several helpful links to help you get familiar with Entity Framework Development Workflows and the code-first workflow.

Implementation of the Web Service Interface

In my last post, we discussed the interface of the WCF application and how it forms a mutually binding contract, between the client and the service. The client must make their request in a format the service is expecting, and the service must fulfill the request in the format specified in the contract. This is all defined in the operation contract of the IArtService interface.

  • The request must be an XMLHttpRequest using the “GET” verb
  • The “GET” request must specifically request access to the ArtService.svc and the GetArtists method
  • The service must respond to the request with data serialized into the Json format

Here is a simple JavaScript function which would satisfy the contractual requirements for a request;

Once again, here is the IArtService interface where the mutually binding contract between the service and clients is defined;

As you can see, the interface also uses the System.Runtime.Serialization and System.ServiceModel.web name spaces to fulfill the request.

Now, lets examine the implementation of the IArtService interface. Here is the source code of the ArtService class which implements the IArtService interface;

As I stated in an earlier post, the purpose of the Art Service Class is not to expose the business logic of the World of Art web app. Instead, the purpose of the Art Service, is to simply expose specific data elements from the World of Art domain, which can be served upon request, to various software clients. In order to retrieve data from the world of art domain, the ArtService class references two name spaces from the WorldOfArtWebApp;

  • ArtWorldObjects
  • WorldOfArtWebApp.DataAccess

With these references, the GetArtist() method can reuse components of the WorldOfArtWebApp from the Data Access Layer and the Data Model defined in the Entity Framework.

The GetArtist() method is bound by the Operation Contract, defined in the IArtService interface, to return a list of artist objects. This requirement is satisfied by simply creating a new instance of the ArtWorldCollectionArtist Class, and accessing the collection of artist objects in the ArtWorldCollection property. The collection of artist objects is retrieved from the WorldOfArtContext, generated from the Entity Framework. The WCF web service will serialize each of this artist objects into JSON format as specified in the operation contract.

In my next post, I will discuss how to specify which properties of the Artist object are exposed to the web service. Also, here is the source code for the ArtWorldCollectionArtist class, invoked by the GetArtist() method.

Data Access Layer – Implementing the Abstract Interface

In this post, I will demonstrate how I implemented the abstract interface called IArtWorldCollections. Below are two code snippets illustrating the implementation;

Following is the C# source code of the IArtWorldCollections interface. The interface has the following components;

  • A read only property, called WorksOfArtContext of type object context. The entity data model is an Object Context Class
  • A read only property, called ArtWorldCollection of type generic list. The Generic List Class Represents a strongly typed list of objects that can be accessed by index. It Provides methods to search, sort, and manipulate lists.
  • A read only property, called ExceptionMessage of type string. This property will store the message text, generated by any exceptions, thrown by any operations, performed in the methods of the class implementing the interface.
  • The final component is a method, called GetArtCollectionData, which accepts no parameters and returns no value. The purpose of this method, is to populate objects in the World Of Art Domain, with data from the World of Art entity data model. Then add each object, to the generic list property, called ArtWorldCollection.

Now lets implement this interface in an actual C# class. Following is the C# source code, for a class I added to the data access layer. The class is called ArtWorldCollectionArtist, and as you can see, it implements the IArtWorldCollection interface, replacing the generic type T, with an object of type Artist, from the World of Art Domain. We replaced the generic object type of T, with the object type of Artist, because the purpose of this implementation is to generate a list of Artist objects, populated with data through the entity data model.

The three properties of the IArtWorldCollection interface are implemented with the following protected members of the class;

  • m_context, of type WorldOfArtContext, from the object context class of the WorldOfArt entity data model
  • m_artistList, of type Generic List, object type of Artist replaces the generic T type
  • m_exceptionMessage, of type string

The constructor method of the ArtWorldCollectionArtist class, initializes the protected members based on their object types. The constructor method also calls the GetArtCollectionData() method. In this method I use the Language-Integrated Query(LINQ) syntax available in C#, to perform a query against the World Of Art data model. We will cover LINQ in more detail in a future post. I employ a ForEach loop, to load the results of the query into the Artist List Collection. Notice how the query is not against a SQL Server databse table, instead the query is against the Artist property of the object context, in the World of Art Data Model. Therefore, I can create a new instance of the Artist object from each Artist in the result set of the query. I can populate the properties of the Artist object, with data from the properties of the Artist class in the data model.

Finally, with the implementation of the IArtWorldCollection interface, we have achieved the separation of concerns we’ve been striving for. Notice how the ArtWorldCollectionArtist class has no concern for the source of the artist data. There is no code for opening and closing a connection to the database server. No need for hard coded SQL commands like “SELECT FirstName, LastName, BirthDay, City, Country, TypeOfArtist FROM aspnet_Artist” which can be severely impacted by changes to the database tables. The coding task is simplified by the entity data model, because now I’m coding against classes and properties, instead of hard coding table and column names. The hard tasks, of connecting to the database and accessing the tables of the database, have been abstracted into the entity data model. Even if the source of data changes from a Microsoft SQL Server database, to an ORACLE database, or even a data service, the ArtWorldCollectionArtist class would not be impacted by any of these changes.

One last comment on implementing a generic interface for data access, through the entity data model. The payoff for using this approach will continue to increase, as we further implement the interface, to access data and populate other elements in the World of Art domain; such as the works of art created by the artist. More on this in my next post.

The Data Model Layer

As discussed in the last post, we are going to apply a layered architectural structure, to the World of Art web app. The first layer we are going to develop, will be called the Data Model Layer. The purpose of this layer is to achieve a separation of concerns. To create distance and independence, between code supporting the application’s user interface, and code supporting access to the data source.

We will begin by adding an object model to the application. This object model is based on the World Of Art Relational Database, developed in a prior iteration. See Generating Data Model Based on Relational Database, for step by step instructions on generating the data model. As mentioned in previous posts, our data model layer is based on the Microsoft ADO.NET Entity Framework.

Now that the data model is generated, I’m going to display another illustration of the World of Art database diagram, which the data model is bases on. This diagram is more detailed, and shows the properties of each column of the two tables, currently in the database. Also, remember the “one-to-many” relationship between an artist and their works of art. An artist can create one or more works of art. This relationship is illustrated by the key and infinity symbols in the diagram. Please keep this diagram in mind, when we examine the data model diagram, based on this database.

Database Diagram for Data Model

World of Art Database Diagram

The next diagram illustrates the data model, which is based on the World of Art database. I used the Entity Data Model Wizard in Visual Studio 2010, to generate the data model. The data model has two classes, based on the two tables in the World of Art database. The Artist table and the Works of Art table, have been abstracted into two separate classes. The columns of the tables are now represented by the properties of each class. Also, notice how the one-to-many relationship between an artist and their works of art is maintained.

Data Model based on World of Art Database

Data Model based on World of Art database

The Entity Data Model Wizard in Visual Studio 2010, not only generates the entity data model diagram illustrated above, it also generates an entire C# code file, which the diagram is based on. The following image is a class diagram I generated in Visual Studio 2010. It’s based on the WorldOfArt.Designer.cs file which was generated by the Entity Data Model Wizard. As you can see, the wizard actually generated three classes. The one in the middle is the WorldOfArtContext class, it inherits the System.Data.Objects.ObjectContext class. The other two classes are based on the two tables in the World of Art database, and inherit the System.Data.Objects.DataClasses.EntityObject class. Like any typical C# class, they have private members and public properties, along with a wide range of partial methods and event handlers, for updating the tables.

WorldOfArt.Designer.cs Data Model Class Diagram

Class Diagram Based on World of Art Data Model

Finally, lets take a look at the World Of Art solution in Visual Studio, with the newly added Data Model layer. The highlighted folder, in the illustration below, represents the Data Model Layer in the World of Art project solution. The folder contains two files;

  • The WorldOfArt.edmx file, is the data model diagram. It can be viewed and modified, in the Entity Data Model Designer, in Visual Studio.
  • The WorldOfArtDesigner.cs file, is the C# source code of the Entity Data Model.
Data Model Layer in Solution Explorer

Data Model Layer in the World of Art Project Solution

In my next post, I’ll discuss the benefits derived from building a Data Model Architectural Layer, and an Entity Data Model.