Author Archives: Velcrow
Entity Framework 4.1 Code First
Introduction
In this post I will focus on Entity Framework 4.1 Code First technology which allows developers to first code their domain and from that code generate database without writing any line of SQL code. Such approach is encourage by Domain Driven Development (DDD) methodologies since they states that creating a database first results in more data centric model than it should be obtained.
Problem definition
Entity Framework 4.0 has many advantages and really makes creating data access layer very easy. But it also has some disadvantages. One of the biggest drawbacks is fact that entity class created by EF are not persistence ignorant – they contains many informations about way of storing them in database. Such approach breaks one of the most important principle of object oriented development – the separation of layers. As a solution to this problem Microsoft presented POCO objects in EF – entity classes which are persistence ignorant ( they can be coded or created automatically by a template based on T4). But many developers and specialist were still unhappy – EF 4.0 required to first create database and the model and at the end create the POCO classes and map them to the model. Such solution were discourage by DDD methodologies which states that the first thing should be coding classes not database.
Solution
The Entity Framework 4.1 release is built on top of the 4.0 release of the EF. The Entity Framework 4.1 introduces a new DbContext API, and enables Code First development. Code First enables you to define your model by using C# or Visual Basic .NET classes, configure the model and generate a database schema from it, or map your model to an existing database. Now, I will describe several basic steps for creation very basic Code First model and generating database on bases of it. The first step is creating a new class library project and adding all references needed by EF 4.1 ( this can be done easily by NuGet Package Menager: Install-Package ”EntityFramework” ). Next step is coding our model. Below, I present three classes representing simplified version of Library model – class Book related one-to-many with class Genre and releted many-to-many with class Author.
public class Genre
{
public int ID { get; set; }
public string Name { get; set; }
}
public class Author
{
public int ID { get; set; }
public String Name { get; set; }
public IList<Book> Books { get; set; }
}
public class Book
{
public int ID { get; set; }
public string Title { get; set; }
public Genre Genre { get; set; }
public IList<Author> Authors { get; set; }
}
Next step is creating a context class which represents our database and has to inherit from DbContextclass.
public class LibrayContext : DbContext
{
public IDbSet<Book> Books { get; set; }
public IDbSet<Author> Authors { get; set; }
public IDbSet<Genre> Genres { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Book>()
.HasMany<Author>(a => a.Authors)
.WithMany(b => b.Books)
.Map(m =>
{
m.ToTable("BooksAuthors");
m.MapLeftKey("BookID");
m.MapRightKey("AuthorID");
}
);
}
}
As we can see the sets of entities are represented by generic IDbSet interfaces. Another important fact is implementing many-to-many relationship what is done by function OnModelCreating. In this function we define points where exist many-to-many relationship and than we map this relationship to the another table.
And this is all! Now we can create small test program by creating new project ( i.e. Console Application) and manipulate on some data as in normal EF ( using LINQ to Entities or EntitySQL). After first invoking of any statement over database it will be created on the server. Below I present the database schema which I obtained from above Code First model.
Conclusion
In this post I presented Entity Framework 4.1 Code First API. Using it allows developers to create well defined domain models based on DDD which are persistence ignorant and don’t break layer separation rule. In next posts I will describe how to extend POCO classes by some methods ( due to layer separation and definition of POCO it shouldn’t be done by just adding methods to above definitions) and provide validation for them.
Factory Pattern
Introduction
In the previous post I described using the Repository pattern to encapsulate set of Entities. The next step is creation an class which will be responsible for creating those repositories. It will be an implementation of Factory pattern ( simplified version of Factory Method pattern).
Problem definition
The Factory Design Pattern is probably the most used design pattern in modern programming languages like Java and C#. Its aim is to create objects without exposing the instantiation logic to the client. It also refers to the newly created object through a common interface. Another important factor is fact that we usually implement Factories using also Singleton pattern.
A singleton is a class which only allows a single instance of itself to be created, and usually gives simple access to that instance. In this post I’ll present also thread-safe implementation of this pattern.
Solution
Let me remind a generic implementation of Repository pattern which I presented in the previous post.
interface IRepository<T> where T : class
{
IEnumerable<T> GetAll();
IEnumerable<T> GetByQuery(Expression<Func<T, bool>> where);
T GetByID(int ID)
void Delete(T entity);
void Add(T entity);
}
The factory we want to create has to fulfil several requierments:
- It must contain generic function creating repositories
- The repositories has to be refereed through IRepository<T> interface
- It must be singleton
- It must be thread-safe
First of all I’ll implement the Factory satisfying two first conditions – simple class with one function for creating Repositories.
public class RepositoryFactory
{
public IRepository<T> GetRepositoryInstance<T, TRepository>()
where TRepository : IRepository<T>, new() where T : System.Data.Objects.DataClasses.EntityObject
{
return new TRepository();
}
}
As You can see it is rather simple. The function creating classes is an generic function which takes two types – the first one is a type of Entity which repository we are going to create, and the second one is a type of Repository we are going to create. As You can see, despite the fact that we create objects of concrete repository the function is returning IRepository<T>. This implementation is rather simple but contains one big drawback – someone can create many objects of Factory class what is absolutely not necessary. So let’s make our Factory a singleton.
public sealed class RepositoryFactory
{
private static RepositoryFactory _instance;
public static RepositoryFactory Instance
{
get { return _instance ?? (_instance = new RepositoryFactory()); }
}
private RepositoryFactory()
{
}
public IRepository<T> GetRepositoryInstance<T, TRepository>()
where TRepository : IRepository<T>, new() where T : System.Data.Objects.DataClasses.EntityObject
{
return new TRepository();
}
}
The above solution presents one of the most popular Singleton Design Pattern implementation. The constructor of class is private so we cannot just create an Factory object. The access to object is get by an Instance property ( which, BTW, contain also so Lazy Loading features – the object is created only when it is need, not during program start ) which can return only existing object of this class. Only this instance is able to invoke a function which creates repositories.
As hinted at before, the above is not thread-safe. Two different threads could both have evaluated the test if (instance==null) and found it to be true, then both create instances, which violates the singleton pattern. Note that in fact the instance may already have been created before the expression is evaluated, but the memory model doesn’t guarantee that the new value of instance will be seen by other threads unless suitablememory barriers have been passed. Below solution presents simple thread-safe mechanism base on lock keyword.
public sealed class RepositoryFactory
{
private static RepositoryFactory _instance;
private static readonly object _padlock = new object();
public static RepositoryFactory Instance
{
get
{
lock (_padlock)
{
return _instance ?? (_instance = new RepositoryFactory());
}
}
}
private RepositoryFactory()
{
}
public IRepository<T> GetRepositoryInstance<T, TRepository>()
where TRepository : IRepository<T>, new() where T : System.Data.Objects.DataClasses.EntityObject
{
return new TRepository();
}
}
Conclusion.
This post presents usage an implementation of next, two popular Design Patterns – the Factory Pattern used for creation of objects from same family ( e.g. implementing same Interface) and Singleton Pattern which ensures that there will be only one object of given class in a application -the presented solution is also thread-safe what is very important in case of growing popularity of parallel programming methods.
Entity Framework + Repository + Unit of Work
Introduction
The topic of this post is presentation an implementation of two quite popular data access patterns – Repository and Unit of Work – in Entity Framework.
Problem definition
Repository mediates between the domain and data mapping layers, acting like an in-memory domain object collection. Conceptually, a Repository encapsulates the set of objects persisted in a data store and the operations performed over them, providing a more object-oriented view of the persistence layer. Repository also supports the objective of achieving a clean separation and one-way dependency between the domain and data mapping layers.
Unit of Work maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems. Since EF contains several features of the UoW “out of the box” in this context we use UoW pattern when we need some additional behaviours ( mostly connected with concurrency checking) not provided by EF.
Solution
Firstly let’s define the interface representing Unit of Work pattern:
interface IUnitOfWork
{
void Commit();
void Rollback();
}
Next is an concrete class implementing this interface. We can notice that main work is done by ObjectContext class.
class UnitOfWork : IUnitOfWork, IDisposable
{
private readonly ObjectContext _context;
public UnitOfWork(ObjectContext context)
{
_context = context;
}
public void Commit()
{
//Some additional operations
// ...
_context.SaveChanges();
}
public void Rollback()
{
//Some additional operations
// ...
_context.Refresh(RefreshMode.StoreWins, object);
}
public void Dispose()
{
_context.Dispose();
}
}
When Unit of Work is created we can start implementing Repository pattern. As in previous example we start with an interface for this pattern.
interface IRepository<T> where T : class
{
IEnumerable<T> GetAll();
IEnumerable<T> GetByQuery(Expression<Func<T, bool>> where);
void Delete(T entity);
void Add(T entity);
}
Than the abstract repository class is created. While in UoW implementation main part of job is done by ObjectContex class, here the ObjectSet<T> is most useful.
abstract class AbstractRepository<T> : IRepository<T> where T : class
{
private readonly IObjectSet<T> _objects;
public AbstractRepository(ObjectContext context)
{
_objects = context.CreateObjectSet<T>();
}
public IEnumerable<T> GetAll()
{
return _objects.ToList();
}
public IEnumerable<T> GetByQuery(Expression<Func<T, bool>> where)
{
return _objects.Where(where);
}
abstract public T GetByID(int ID);
public void Delete(T entity)
{
_objects.DeleteObject(entity);
}
public void Add(T entity)
{
_objects.AddObject(entity);
}
}
The last step is creating a repository class for each our entity class. Below I present an example of such concrete repository.
class BookRepository : AbstractRepository<Books>
{
public BookRepository(ObjectContext context)
: base(context)
{
}
public override Books GetByID(int ID)
{
return _objects.First(n => n.ID == ID);
}
}
Eaxmple code
using (PracaEntities context = new PracaEntities())
{
IUnitOfWork unitOfWork = new UnitOfWork(context);
BookRepository bookRepo = new BookRepository(context);
bookRepo.Add(new Books());
unitOfWork.Commit();
}
Conclusion
This post presents usage of two very popular patterns – Repository and Unit of Work – in Entity Framework. Presented implementation gives us a possibility of encapsulation ObjectContext class in UnitOfWork class. We also have possibility of developing this class with more features and behaviours such as concurrency checking during save operations. The second part of post presented the implementation of repository pattern. The presented solution is generic and very easy for future development. Repository pattern provides developers a easy data access façade for each object set and defines most popular operations done on data sets.
Entity Framework: many-to-many relationships
Introduction
Before I start with design patterns and all information about them I have to give You some information about one feature of Entity Framework which will be very useful in our future reflections. The topic of this post is many-to-many relationship handling in Entity Framework.
Problem definition
A many-to-many relationship is a type of cardinality that refers to the relationship between two entities A and B in which A may contain a parent row for which there are many children in B and vice versa. For instance, think of A as Authors, and B as Books. An Author can write several Books, and a Book can be written by several Authors. Because most database management systems only support one-to-many relationships, it is necessary to implement such relationships physically via a third junction table, say, AB with two one-to-many relationships A -> AB and B -> AB. In this case the logical primary key for AB is formed from the two foreign keys. Thus, assuming that EF tries to map all tables on the classes directly we should get another, additional class which is created for the junction table and it contains only two navigational properties ( so called Associative Entity).
Solution
Entity framework handles tables participating in many-to-many relationship in a nice way. If the junction table only consists of the foreign keys and no other columns, then that table is omitted by EF and the two sides get a navigational property exposing a collection of the other side. If the junction table contains other fields as well (e.g. the table has its own primary key column), then that junction table is included in the model with many-to-one relationships with both the participating tables.
Please consider following example presenting many-to-many relationship between Books and Authors
The generated Entity Model will look something like:
Thanks to such a way of mapping objects by Entity Framework we can easily manipulate and query data. Bellow I will present several examples of querying against this data.
Example Code
Finding an authors collection for book of given title.
Books searchedBook = context.Books.First(n => n.BookDescriptions.Title == searchedTitle); IEnumerable<Authors> authorsCollection = searchedBook.BookDescriptions.Authors;
Finding a titles collection for given author
Authors searchedAuthor = context.Authors.First(n => n.Surname == searchedSurname); IEnumerable<string> titleCollection = searchedAuthor.BookDescriptions.Select(n => n.Title);
Finding a book list for given author
Authors searchedAuthor = context.Authors.First(n => n.Surname == searchedSurname); IEnumerable<Books> bookList = searchedAuthor.BookDescriptions.Select(n => n.Books.First());
Limitations
Unfortunately ( or maybe fortunately) EF behaves in above present way only in case of junction tables which contains only two foreign keys. But, of course, it is not a drawback – if You had had to insert additional columns into junction table it represents not only simple association between two entities but rather an association class.
Conclusion
I hope You like this short introduction to handling many-to-many relationships in Entity Framework 4.0. In the beginning I’ve defined a problem which could have happened during using O/R mapping and than I’ve explained how EF handles such a situation. Next, some example source code has been presented. At the end I also have presented some limitations of EF in this area.
Hello world!
Hello,
First of all, I would like to thank You all for visiting this blog and reading this note ( especially You, Reader) . I hope that You’ll like my writing style and find topics I’ll write about quite interesting.
But at the beginning let me introduce myself. My name is Krzysztof Cieślak and I am 21-years-old developer and software designer / architect. Currently I’m studying Information Technology at Technical University of Lodz ( Poland ) and, in the nearest future, I’ll move for one year exchange to the Technical University of Denmark. I’ve been interested at programming for 4 or 5 years – firstly I was working mainly with C++, then I’ve done several projects connected mainly with SQL. About two years ago I’ve started beeing interested at Microsoft technologies ( different than Windows OS
), especially on .NET framework and C# programming language. During this two years ( apart from boring academical subjects) I’ve been working on over a dozen projects implemented in C# ( mainly ADO.NET + WPF ), lastly I’m especially focused on EF and ASP.NET ( I’m working on interested project for university’s broadcast centre).
On this blog I hope to write about interesting topics – I’ll mainly focus not on some very detailed technical aspects of different API ( since there are many more better sources of such information, for example, blogs of Microsoft workers or MVPs ). I’ll try to focus mainly on using design patterns in C# (it can be easily generalised for different OO languages such as Java or C++)- aspects which is often forgotten by many programmers, especially oes with small busies experience. I’ll also write some info about interesting libraries which I’ve used nin the past ( for example EmguCV – Computer Vision Library for C# or Obout ASP.NET controls )
Best whishes,
Velcrow


