Generic Repository with Entity Framework

My first NuGet package and OSS project is live :)

What an exciting day! Lots of new releases announced in the last couple of days so why not add to the funfair and release my own OSS? This is a piece of code that I had to develop for a client and it took some effort. During the development of this library I tried to make as generic and modular as possible, which made it quite easy when I decided to share it with the community. The project is now live and there is a public repo on GitHub in hope that I can help someone else not to re-invent the "my square wheel".

It is not ground-breaking or exciting, but it works and serves a very important need - to be able to manage the state of complex object graphs when performing CRUD operations in Entity Framework.

Entity Framework is Microsoft's ORM, very similar to nHibernate etc. If you haven't used Entity Framework you should have a quick look as it is awesome and can make database operations a breeze, abstracting most of the nighty-gritty stuff and letting you focus on the code :)

During the latest TechEd in May, Microsoft announced EF7 which sounds pretty amazing and it is a complete re-write of the old codebase while maintaining full compatibility with older code. Of course, certain things are thrown away/deprecated, but from what I've seen, anything code you've writen using EF5 or later is safe. There is a great video with lots of demos on EF7 here.

Jump to 1:03:00 to see the EF7 demo

And this brings me back to my OSS. A generic repository for Entity Framework with excellent support for object graphs. An object graph, is a collection of related entities/objects such as teacher+students+classes. Think of it this way
=> A teacher has many students and attends many classes

As a result, when you work with complex objects you may end up with a situation where a student is modified, another student is added and 2 students are removed and the teacher has to drop a class. This is a pretty common scenarion in production apps and something that EF is not perfectly equipped to handle easily.

My generic repository allows developers to manually manage the different objects' state and ensure that when they call UnitOfWork.Save() the appropriate CRUD operations are performed.

"With great power comes great responsibility"

Well, it had to be said and I'm sure that you are thinking it. What happens if I mess up the objects' state? Well, in that case you're on your own. Just kidding, but please be careful when you work with multiple complex objects and try to keep your operations are as atomic as possible to avoid this scenario.

You can check the code on GitHub or download the NuGet package directly into your solution

I know it's early days, but I've had 7 downloads already!

Feel free to comment here or on GitHub or on Twitter

Happy Coding...

Find me on twitter: @christosmatskas

  • Share this post on