January 2010 - Posts
Entity Framework at Sela Open House
Yesterday, even though I’m currently sick (I have the flu), I delivered
a session about Entity Framework at Sela Open House event.
In the session I introduced Entity Framework, talked about the
EDM, explained how to query and manipulate data and in
the end talked about what is coming in EF4.
I want to thank all the attendees who came to hear the session.
As I promised, I uploaded the session slide deck and demos to
my SkyDrive and you can download them from here.
Enjoy!
Don’t Repeat Yourself
Today while I was
doing code review
I found myself
writing a new
generic function
instead of one
piece of code
that was repeating
itself in the
developer’s code.
When you write
code sometimes you
have to duplicate
some piece of code.
When it occurs, this
is the best time to
think of refactoring your functionality.
A lot has been written about DRY principal this post is my opinion
about it.
The DRY Principal
Don’t Repeat Yourself or DRY is a very good practice when we are
writing code. It helps to produce a more reusable and maintainable
code. When you don’t follow DRY whenever a functionality that
you “Copy & Paste” all over your code will change you’ll have
the taste of one of the developer horrors -
to find all the places in the application that you duplicated the
functionality and to update it. Not being able to find all the places will
result in a non functioning application or other errors. Since changes
always occur during the life time of an application following the
simple DRY principal can prevent you a lot of headaches.
Example
Lets look at the code that I helped the developer to refactor:
private void ValidateContactDetails()
{
var validator = ValidationFactory.CreateValidator<ContactDetails>();
var results = validator.Validate(uc.DataSource);
if (results.Count > 0)
{
ValidationError.DisplayError(results.First().Message);
}
}
This code validate a contact details entity using the
Validation Application Block. Since the code was repeated in more
than one place but with different object types and different data
sources then I created the following method instead:
public void ValidateEntity<T>(object dataSource)
{
var validator = ValidationFactory.CreateValidator<T>();
var results = validator.Validate(dataSource);
if (results.Count > 0)
{
ValidationError.DisplayError(results.First().Message);
}
}
Now instead of duplicating the functionality of validation with a
lot of functions that perform the same thing we have only
one function that perform the same thing but is more generic.
This is much better!
Summary
Lets sum up, to achieve code quality you shouldn’t repeat yourself.
”Copy & Paste” helps to create code faster but it has the ability
to make your code very poor when it is being used without thinking.
Whenever you repeat some piece of code all over the place it’s a very big
sign for you that you need to refactor your code. One of the horrors of
a developer is to find all the duplications in a code base and change
some simple functionality.
So don’t repeat yourself!
Table Per Concrete Type Inheritance in Entity Framework
The last inheritance
mapping that I’m
going to write about
is the Table Per Concrete
Type inheritance (TPC). This
inheritance type is
very rare but you should
be aware of how to create it when it is needed.
You can read about TPT and TPH from here and from here.
Table Per Concrete Type Definition
The TPC inheritance occurs when we have two tables with
overlapping fields in the database. Such a thing can occur
in situations that we create an history table that all historical
data is transferred from the main table to it.
In the example I’m going to use the following database schema:
As you can notice I have a Department table and a DepartmentHistory
table. They both have overlapping fields.
TPC Example
The following steps will help you to understand how you can create
a TPC inheritance mapping. I’m going to use the exactly database
from the first figure I showed.
Step 1
The first step is to create the Entity Data Model from the database.
Here is the EDM I’m going to use in the example:
Step 2
Create an inheritance from OldDepartment (which is mapped to
DepartmentHistory table) to Department entity. In order to do that
in the designer surface click on the right mouse button and use the
Add –> Inheritance menu item.
In the Add Inheritance dialog make the Department the base entity
and the OldDepartment derived entity.
After you do this the model will look like:
Step 3
Since we have overlapping tables remove all the properties of OldDepartment.
These properties are going to be taken from the Department entity.
The model should look like:
Step 4
Now it is time for the mapping. In the Mapping Details View you
will notice that the only available property for mapping is the
DepartmentID property. Map it in the OldDeprtment.
All the other mapping details will be needed to be edit manually
in the Xml editor.
Step 5
Open the model in Xml editor and seek for the mapping of OldDepartment
entity in the MSL part. You will see that the Departments set is mapped
as:
<EntitySetMapping Name="Departments">
<EntityTypeMapping TypeName="IsTypeOf(SchoolModel.Department)">
<MappingFragment StoreEntitySet="Department">
<ScalarProperty Name="DepartmentID" ColumnName="DepartmentID" />
<ScalarProperty Name="Administrator" ColumnName="Administrator" />
<ScalarProperty Name="StartDate" ColumnName="StartDate" />
<ScalarProperty Name="Budget" ColumnName="Budget" />
<ScalarProperty Name="Name" ColumnName="Name" /></MappingFragment></EntityTypeMapping>
<EntityTypeMapping TypeName="IsTypeOf(SchoolModel.OldDepartment)">
<MappingFragment StoreEntitySet="DepartmentHistory">
<ScalarProperty Name="DepartmentID" ColumnName="DepartmentID" />
</MappingFragment>
</EntityTypeMapping>
</EntitySetMapping>
Copy all the property mappings from Department to OldDepartment
mapping and that is all. The code will look like:
<EntitySetMapping Name="Departments">
<EntityTypeMapping TypeName="IsTypeOf(SchoolModel.Department)">
<MappingFragment StoreEntitySet="Department">
<ScalarProperty Name="DepartmentID" ColumnName="DepartmentID" />
<ScalarProperty Name="Administrator" ColumnName="Administrator" />
<ScalarProperty Name="StartDate" ColumnName="StartDate" />
<ScalarProperty Name="Budget" ColumnName="Budget" />
<ScalarProperty Name="Name" ColumnName="Name" /></MappingFragment></EntityTypeMapping>
<EntityTypeMapping TypeName="IsTypeOf(SchoolModel.OldDepartment)">
<MappingFragment StoreEntitySet="DepartmentHistory">
<ScalarProperty Name="DepartmentID" ColumnName="DepartmentID" />
<ScalarProperty Name="Administrator" ColumnName="Administrator" />
<ScalarProperty Name="StartDate" ColumnName="StartDate" />
<ScalarProperty Name="Budget" ColumnName="Budget" />
<ScalarProperty Name="Name" ColumnName="Name" />
</MappingFragment>
</EntityTypeMapping>
</EntitySetMapping>
Step 6
Test the created inheritance. The following code will print out
all the departments and then all the old departments in the
database.
using (var context = new SchoolEntities())
{
var departments = context.Departments.OfType<Department>();
foreach (var department in departments)
{
Console.WriteLine(department.Name);
}
var oldDepartments = context.Departments.OfType<OldDepartment>();
foreach (var department in oldDepartments)
{
Console.WriteLine("old: {0}", department.Name);
}
}
Console.ReadLine();
Summary
Lets sum up, in the last post about inheritance types I explained
what is Table Per Concrete Type Inheritance and showed how
to map it in EF. There are more ways to customize the conceptual model
that we have in EF like using Complex Types, DefiningQuery and etc.
Even though, inheritance mapping is very useful in order to express our
conceptual model as we see it in Object Oriented.
Table Per Hierarchy Inheritance in Entity Framework
In the second
inheritance mappings
tutorials I’m going to
write about the
Table Per Hierarchy
(TPH) inheritance
mapping. If you want to read
about the first mapping I showed go to the Table Per Type post from
here.
Table Per Hierarchy Definition
In TPH the inheritance tree is create through one table only.
The TPH inheritance depends on a conditional mapping which is
defined by a condition such as a discriminator database field.
The condition is used to define records as different types.
For example, in the following database schema the Person table
includes a TPH inheritance:
As you can see the table holds two different fields from two
different types: HireDate (which belong to a professor type)
and EnrollmentDate (which belong to student type). The table
also includes an integer discriminator field which is called PersonType.
When PersonType equals 1 the person type is a professor and when
it is 2 the type is student.
TPH Example
The following steps will help you to understand how you can create
a TPH inheritance mapping. I’m going to use the exactly database
from the first figure I showed.
Step 1
The first step is to create the Entity Data Model from the database.
Here is the EDM I’m going to use in the example:
We are going to use only the Person entity for the TPH demonstration.
Step 2
From the designer surface use the Add –> Entity and add two entities:
Professor and Student.
Make Person entity their base type.
After that the model should look like:
Step 3
Move the HireDate property to the Professor entity and the
EnrollmentDate property to the Student entity. Also remove
the PersonType property from Person because it is going to
be our discriminator field.
Step 4
In the Mapping Details View map the Student entity and the
Professor entity to the Person table. Also map the relevant
properties to the fields in the database. The following figure
shows how to map the student entity:
Step 5
Add a condition to the entities using the Mapping Details View. The
condition should be on the PersonType field and should indicate that
if PersonType equals 1 the person is a Professor type and if the
PersonType equals 2 the person type is a Student. the following
figure shows how to do it in the Student type:
Step 6
Since Person is a base type which is an abstract type we need to
indicate that it is abstract. Point on the Person entity and press
F4 to open it’s properties dialog. In the dialog turn the abstract
flag to True.
Step 7
Test the inheritance mapping. The following code will print the
number of people in the database and also the number of professors
and students:
using (var context = new SchoolEntities())
{
var query = from person in context.People
select person;
Console.WriteLine("All People: " + query.Count().ToString());
var query1 = from student in context.People.OfType<Student>()
select student;
Console.WriteLine("Students: " + query1.Count().ToString());
var query2 = from proffesor in context.People.OfType<Professor>()
select proffesor;
Console.WriteLine("Professors: " + query2.Count().ToString());
}
Console.ReadLine();
Summary
Lets sum up, in the post I explained what is Table Per Hierarchy
inheritance and showed how we can create that inheritance
in a specific model. The use of TPH is common and sometimes
can lead to very big tables which include a lot of fields. Since it is
a bad habit to create very big tables, I suggest to use TPH with TPT.
In the last post in this series I’m going to explain what is
Table Per Concrete Type inheritance and how to use it in EF.
Table Per Type Inheritance in Entity Framework
The first inheritance
mapping I’m going to
show is called
Table Per Type
or TPT. Before
I start with the example
lets define what is TPT.
Table Per Type Definition
TPT is an inheritance described in the database with separate tables.
Every table provides additional details that describe a new type
based on another table which is that table’s parent.
In the following database ERD the OnlineCourse table is a concrete
type of Course:
As you can see the CourseID of both Course and OnlineCourse table
are the same identity.
TPT Example
The following steps will help you to understand how you can create
a TPT inheritance mapping. I’m going to use the exactly database
from the first figure I showed.
Step 1
The first step is to create the Entity Data Model from the database.
Here is the EDM I’m going to use in the example:
As you can see I created an EDM with only the relevant tables for
simplicity. Also, pay attention to the association that was created
(1 - 0..1) between the tables. This is happening because of the use of
the same ID in both of the tables.
Step 2
After we have our EDM ready to work we need to define the
inheritance instead of using the created association.
First remove the association by clicking on the association in
the designer and pressing delete. Then from the designer surface
press on the right mouse button and use the Add –> Inheritance
to open the Add Inheritance dialog.
In the Add Inheritance dialog make the Course the base entity and
the OnlineCourse the derived entity like in the following figure:
We you finish you will have an inheritance arrow between OnlineCourse
and Course like:
Step 3
After we have created the inheritance we need to fix our model.
The CourseID field in the OnlineCourse isn’t relevant anymore since
it is part of the base entity. So lets remove it. Also we need the
CourseID database field to be mapped to something which is the
parent CourseID:
That is it for this kind of model. There will be more model fixing when
we have associations to other entities.
Step 4
Test the created model. The following piece of code will print the
count of the online courses we have in our database:
using (var context = new SchoolEntities())
{ var query = context.Courses.OfType<OnlineCourse>().Count();
Console.WriteLine("Number of online courses: {0}", query); Console.ReadLine();
}
As you can see I’m using the OfType method which enable me to
do operations on derived types.
Summary
Lets sum up, I showed how to use Table Per Type inheritance in
Entity Framework. As I wrote in a previous post this kind of mapping
isn’t used only by EF and it is also used by other ORMs. In the
next post in this series I’m going to describe and show the Table
Per Hierarchy inheritance.
Entity Framework Inheritance Types
In Sela SDP
conference I was
asked if Entity
Framework supports
inheritance mapping.
The answer I gave
was a small 25 minutes improvised session which I gave after
the EF4 session I had. In the following three posts I’m going to
explain the main three inheritance ways that you can use with EF.
These ways are supported in other ORMs as well.
Why to Use Inheritance?
One of the ORMs main purposes is to enable us the domain developers
to create a conceptual model that resemble our way of thinking about
our domain. Since we use Object Oriented principals like inheritance to
express the domain there is a need to create the inheritances in
the data storages that we use. But how can we create the inheritance
graph in a database and map it within the ORM?
The Main Inheritance Ways
There are three main ways (or combinations of these ways):
As I wrote, I’ll explain every one of these ways and show EF examples
in a follow up series.
Using Repository Pattern with Entity Framework
One of the tools
for reaching for
persistence
ignorance is to
build a facade between
the data access layer and
your business logic. Such facade will prevent the knowledge of
how the data access is working and with which technology. That
abstraction can be achieved by using the Repository Pattern.
In the post I’ll show how you can use the Repository Pattern in order
to make an abstraction layer on top of Entity Framework.
The Repository Interface
When we want to use the Repository Pattern we
start with an interface which will be our data access facade.
I’ll be using the following interface in my example:
public interface IRepository<T>
{
T GetById(int id);
T[] GetAll();
IQueryable<T> Query(Expression<Func<T, bool>> filter);
}
This interface only include some of the functionality which I’ll
put in a repository. You may notice that I removed any CUD
(Create/Update/Delete) operations. In a follow up post I’ll show
how to implement these operations by using the Unit of Work
pattern.
A Repository Implementation
The following is a naive implementation for a department repository:
public class DepartmentRepository : IRepository<Department>, IDisposable
{
#region Members
private SchoolEntities _context;
#endregion
#region Ctor
public DepartmentRepository()
{
_context = new SchoolEntities();
}
#endregion
#region IRepository<Department> Members
public Department GetById(int id)
{
return _context.Departments.
Where(d => d.DepartmentID == id).
FirstOrDefault();
}
public Department[] GetAll()
{
return _context.Departments.ToArray();
}
public IQueryable<Department> Query(Expression<Func<Department, bool>> filter)
{
return _context.Departments.Where(filter);
}
#endregion
#region IDisposable Members
public void Dispose()
{
if (_context != null)
{
_context.Dispose();
}
GC.SuppressFinalize(this);
}
#endregion
}
This is a naive implementation since I hold a context inside my
department repository. A better solution will be to create a
context helper that will be used in order to create contexts when
they are needed. After we have the implementation we can start
using it.
The following code demonstrate how we can use the department
repository:
IRepository<Department> repository = new DepartmentRepository();
foreach (var department in repository.GetAll())
{
Console.WriteLine(department.Name);
}
foreach (var department in repository.Query(d => d.Budget > 150000))
{
Console.WriteLine("department with above 150000 budget: {0}",
department.Name);
}
Console.ReadLine();
Why to use the Repository Pattern?
There are a lot of reasons for using the Repository Pattern.
For example:
- Testability. Using the pattern we can create stubs that
can replace the real data access objects. This can
help us to test our business logic without concerning what the
data access is doing.
- Abstraction. Using the pattern we create an abstraction above
our data access functionality. This abstraction can help us when we
want to change the implementation of the data access without
affecting our business logic code. For example, I had to change
implementation of data access with a call to a web service. Using
the pattern I only needed to change the object that I used and that is
it.
- Dependency Injection. Using the pattern we can use DI containers to
inject the relevant object that we want to use in the code.
Summary
Lets sum up, the Repository Pattern is a very useful pattern to use
when we build data access layers. Like all other patterns sometimes
it can be an overkill in abstraction (in particular in small and simple applications).
In the post I showed one way to create a repository on top of Entity Framework.
I could have used any other data access frameworks as well and this is the beauty
of the pattern. In a follow up post I’ll explain what is the Unit of Work pattern and
will continue building the repository I used in this post so stay tuned.
Defining Custom Functions in Entity Framework
During the SDP conference
I have been asked about the
use of functions inside the EDM.
This post will try to answer one
such question of how to define
a custom function in EF.
Custom Functions in Entity Framework
One of the capabilities of EF since EF1 was the creation of custom
functions inside the SSDL part of the model. After their creation
we could consume them like other imported functions.
In that way we could define functions in the model which were
acting like stored procedures but without being a part of the database.
This of course means that in order to use this feature we needed to
write some XML code inside the SSDL.
Defining a Custom Function
The first thing to do is to open the model in XML editor and to
add a Function element inside the Schema element in the SSDL part of the
XML. Inside the Function element we add a CommandText element which
will hold our T-SQL expression. We can also add to the function parameters.
The following XML fragment shows an example of a custom function:
<Function Name="GetCoursesByCredit" IsComposable="false">
<CommandText>
SELECT *
FROM Course
WHERE Credits = @Credits
</CommandText>
<Parameter Name="Credits" Type="int" Mode="In"></Parameter>
</Function>
After the creation of that function we can use the Add Function Import
wizard to import that function to the ObjectContext:
and then to run a test like this one to see the function in action:
using (var context = new SchoolEntities())
{
var query = context.GetCoursesByCredit(3);
foreach (var course in query)
{
Console.WriteLine(course.Title);
}
Console.ReadLine();
}
Summary
EF enables us to add custom SSDL functions to our model. These
functions can be handled like other imported functions (UDFs or
stored procedures). This feature should be used rarely in my opinion
and only when there is a T-SQL functionality that we must have but
EF doesn’t support.