Closing Another Year
Another year of writing is
over. A lot has happened in
my life during the last year.
Here are some highlights:
- I have a new baby boy
at home :-) - I received a MVP award from
Microsoft. - I started to work in a new
company – Sela Group. - And many more.
Few Stats About my Blog
Subscribed readers by Feedburner: ~350 (first year – ~115). Total blog posts: 219 (first year – 113). Total comments: 421 (first year – 216). Total trackbacks and pingbacks: 368 (first year – 81). Google Analytics summary of last year: - Page Views: 178,589 (first year – 57,539).
- Unique Pageviews: 154,821 (first year – 49,714).
- Average time on site: 03:12 (first year – 02:42).
Top Three Posts Ordered by Number of Views
Tell me how can I Improve My Blog
I’d like to hear from you, the readers of my blog, how can I improve it.
feel free to leave comments such as which topics would you like me to
write about? which things add value to you when you read my blog? or every
comment that you want to share with me in regard to my blog.
Back to Basics – Using MasterType Directive
This post is
a result of
a question that
I got from one
of the developers
that I work with.
The question was
how to use master page properties from an ASP.NET page.
Setting the Environment
The first thing that you want to do is to expose the properties
as public in the master page. For example this is code behind
of a simple master page that exposes the IsPageEnabled property:
public partial class Site1 : MasterPage
{
#region Properties
public bool IsPageEnabled { get; set; }
#endregion
#region Page events
protected void Page_Load(object sender, EventArgs e)
{
}
#endregion
}
The MasterType Directive
When we want to use the property in a page which reference the
previous master page we need to put the inside of it the MasterType
directive:
<%@ MasterType VirtualPath="~/Site1.Master" %>
This directive declare that the master page of a page is strongly type.
By that simple directive we gain access to the master exposed public
properties and methods through the Master property of the page.
For example this is how in the page I’ll call the IsPageEnabled property of
the master page:
public partial class WebForm5 : Page
{
#region Page Events
protected void Page_Load(object sender, EventArgs e)
{
Master.IsPageEnabled = true;
}
#endregion
}
The markup of the page I use:
<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true"
CodeBehind="WebForm5.aspx.cs" Inherits="TestModalDialog.WebForm5" %>
<%@ MasterType VirtualPath="~/Site1.Master" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
</asp:Content>
Summary
Lets sum up, when we use master pages we can expose properties
and methods for the pages. We use the MasterType directive in the
page in order to create a strong type master page inside of it. By
doing that we can pass data from the page to its master.
Very easy and very useful.
Entity Framework Context Lifetime Best Practices
In this post I’m
going to write
about one of the
major decisions
that you need to
take when you use
ORM tools like Entity Framework.
This decision is the context lifetime.
The Problem
Context lifetime is a very crucial decision to make when we
use ORMs. Since the context is acting as an entity cache (it holds
references to all the loaded entities for change tracking and
lazy loading purpose), it may grow very fast in memory consumption.
Also this behavior can cause a memory leak because if we don’t
dispose our context it will have references to all the loaded entities
and by that they will never be collected by the Garbage Collection.
Another problem that raise its ugly head is keeping a context lifetime
to long or to short. If we dispose the context after every database
manipulation or query we won’t enjoy the all the features it holds
(for example change tracking).
For example the following code disposes the context very fast and
shows the problem I talk about:
using (var context = new SchoolEntities())
{
context.AddToDepartments(department);
context.SaveChanges();
}
On the other hand, keeping a long running context is also bad practice.
Sometimes I see developers that use the context as a singleton in their
system. This is very bad since as I wrote it can cause a memory leak.
Also it is bad habit because you will have transactions for longer time
than you should have them. Business transactions and connection
management should be used in very short bursts and only as they are
needed.
My Rules of Thumb
- Web applications – use the context per request. Since in web
applications we deal with requests that are very short but holds
all the server transaction then they are the proper duration for
the context to live in. We will enjoy all the functionality of the
context and it won’t hang up very long.
- Smart clients (Win Forms/WPF etc) – use a context per form.
Since we don’t want to have the context as a singleton for our
application we will dispose it when we move from one form to
another. In this way we will gain a lot of the context’s abilities
and won’t suffer from the implications of long running contexts.
Summery
Managing context lifetime is very crucial decision that we need to take
at the starting of every project. My rules of thumb is context per
request and context per form lifetimes.
Using Unit of Work Pattern with Entity Framework
In a previous post
I explained how
to create a
simple repository
on top of
Entity Framework.
In this post I’ll explain the Unit of Work pattern and how
we can use it with our data access layer.
What is Unit of Work Pattern?
In his famous and developer must read book
“Patterns of Enterprise Application Architecture”, Martin Fowler
defines the Unit of Work as “Maintains a list of objects affected by a
business transaction and coordinates the writing out of changes and the
resolution of concurrency problems.”
What it means is that a unit of work is a context/session/unit object that
tracks the changes of business entities during one business transaction. It is
also responsible for the manage of concurrency problems when they occur.
How to Use The Pattern?
As in the repository pattern we will start with an interface which was
suggested by Martin Fowler:
public interface IUnitOfWork<T>
{
void RegisterNew(T entity);
void RegisterDirty(T entity);
void RegisterClean(T entity);
void RegisterDeleted(T entity);
void Commit();
}
As you can see we register changes of entities inside the unit of work
and in the end of every transaction we commit it using the commit method.
In all the major ORMs out there you get all that functionality within the
session/context objects. It is the unit of work object that holds the details
of every change you do to an entity. Since this is the case you don’t
have to have all the four register methods when you use frameworks
like Entity Framework, NHibernate or other ORMs.
In my example I’m going to use the following unit of work interface:
public interface IUnitOfWork<T>
{
void RegisterNew(T entity);
void RegisterDeleted(T entity);
void Commit();
}
Entity Framework Example
Lets return to the example of the repository I used in the previous post.
I can transform the DepartmentRepository that I’ve built into a
unit of work that handle departments like this one:
public class DepartmentRepository : IRepository<Department>,
IUnitOfWork<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 IUnitOfWork<Department> Members
public void RegisterNew(Department entity)
{
_context.AddToDepartments(entity);
}
public void RegisterDeleted(Department entity)
{
_context.DeleteObject(entity);
}
public void Commit()
{
_context.SaveChanges();
}
#endregion
#region IDisposable Members
public void Dispose()
{
if (_context != null)
{
_context.Dispose();
}
GC.SuppressFinalize(this);
}
#endregion
}
This is a really simple example of how to implement the pattern.
There are a lot of other examples in the web like in the following link:
Entity Framework 4.0 Beta 1 – POCO, ObjectSet, Repository and UnitOfWork
Summary
Lets sum up, every ORM that respect itself (like Entity Framework) includes
implementation for the unit of work pattern. If we want to add our abstraction
layer which include a unit of work then we need to create our implementation.
We will start with an interface such as the one that Martin Fowler suggested.
Then it is our responsibility to track changes and to persist all the work that was
done in a time period as a transaction and also manage concurrency issues.
To Use OSS or Not to Use?
This post is a result of a very big discussion I had with a customer
that I’m currently consulting for. The discussion started because a
project reached its testing phase and to my surprise the QA team
worked with… (don’t be shocked) a primitive excel file to manage
bugs. The testing phase was taking to long because of things like
concurrency (two users can’t edit the excel file at the same time),
synchronization of the same file and many other multi-user or files problems.
Since in my opinion the situation couldn’t go on like this, I contact one
of the managers and suggested to use a bug management system instaed
of using the file. I got the well known answer –
there is no budget and the organization won’t be buying this kind of systems.
I then offered to use BugTracker.NET or other OSS that offer fine bug
management systems. Using such systems will be with no cost so the budget
issue won’t be a problem and the benefits are clear.
This is were I hit the wall!
Apparently there is a very clear guidance in the customer’s organization that
restrict the use of OSS. Even further, the manager came to me and told me that
in his opinion as a consultant I can’t advise to use an OSS (even though I
suggested a tool that I used in the past and it proved itself).
He also told me that he thinks that it can reduce my credibility if I offer to use
open source projects.
Here is my thoughts – bullshit.
There are times that OSS can help you to go forward and not to remain in
Middle Ages. I know that there are pros and cons for using OSS which can
help you decide whether to use them or not in a project but to absolutely
reject a solution because it’s an OSS is stupidity.
In the end they still use the excel file and the schedule for going to production
was postponed in two weeks because of the slow testing phase. Of course it
postponed another project that rely on this project in four weeks.
The delay in the schedule is going to cost the organization more money
then buying a bug management system license.
Making bad decisions can come at you.
The Regulator
Yesterday, I reviewed a regular expression that
was written by one of the developers and
I needed to improve it since it wasn’t performing
the appropriate thing. Since I know The Regulator
tool, I opened it and in 5 minutes I came up with this
regular expression which validate Israeli phone/cellular
numbers:
^0(5[012345678]|6[47]|[23489]){1}(\-)?[^0\D]{1}\d{6}$
With The Regulator I created and checked the expression and
then implemented it in the application.
What is The Regulator?
The Regulator is a free tool that was written by Roy Osherove.
It’s purpose is to help us create regular expressions and also
to test them inside The Regulator application. It allows the
building and verifying of regular expressions and also includes
testing functionality that enable us to see a display of the hierarchical
tree that will be generated by match, replace and split operations.
The following screen show the main screen of The Regulator:
Where Can You Download It?
You can download the tool from here.
Enjoy!
Error CS0029: Cannot implicitly convert type Using WSDL Tool
Today I was
asked by one
of developers
I work with to
check an error
he got after he
generated a proxy class with the wsdl.exe tool from a third party
wsdl he got. The error was generated in runtime when he tried to use
the generated class and it was something like:
Unable to generate a temporary class (result=1).
error CS0029: Cannot implicitly convert type 'A' to 'A[]'
After searching in the internet I found that there is a known bug
where the xsd/wsdl generators don’t produce the correct proxy
class. The problem was that the generated class was produced with
a method call that return a jagged array ([][]) instead of a simple array
of type A ([]). In runtime the serialization of an array doesn’t
produce a jagged array and also the opposite and therefore it generate
the exception only in runtime.
How to fix the Problem?
After generating the C# proxy class from the given wsdl check that
the generated class is correct and if not manually fix all the
problems. The fix for our problem was to remove one of the two []
from the jagged array that was generated.
I hope it will help you if you stumble on this error in the future.
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 let remove it. Also we need the
CourseID database field 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.
More Posts
Next page »