Friday, July 25, 2014

Data Repository for Entity Framework 6, MVC5 / Web API, async actions and some tricks

While there is an ongoing shift in the way applications are being built today and a lot of business and view logic seems to be shifting to the front-end it’s even more crucial to have a data layer that is lean, simple and easy to maintain. Here is one take on a data layer using Entity Framework and ASP.NET.

Entity Framework (EF) is an object-relational mapper for the .NET platform. EF bridges the gap between the data source and domain specific objects thereby eliminating a lot of code and complexity that developers have had to deal with in the past.

EF provides a very powerful layer of abstraction for data programming, eliminating the impedance mismatch between data models and languages that application developers would otherwise have to deal with.

Why choose Entity Framework?

- Increased developer productivity by relieving you of the boring and repeated task of persisting the data that you use in your applications. Also a standard way of doing things so knowledge transfer is easier.

- Developers can focus on business logic and the user experience and let EF generate the necessary database commands for reading or writing data and execute them for you in the database.

- EF is very flexible even letting you map a single entity to multiple database tables or even multiple entities to a single table.

- EF is Microsoft's recommended data access technology for new applications and its generally recommended to use going forward in place of LINQ to SQL or standard ADP.NET

Let’s look at a simple repository based approach using a code first model to perform our database operations against a SQL Server database. We will use the new async actions and a few tricks that might make your development easier. The code first approach lets you define your classes and it will figure out what you're database should look like. It’s generally a good approach for new projects without an existing database.

Let’s start with a Base Model class for all our Model objects. Out base model has an Id which is the primary key and a created and modified date.

Note: Am using latest versions of EF6.1, MVC5 and WebApi2. All our domain classes like the following Person class would inherit from our BaseModel and add properties as needed. We have set length limits on the First and Last Name which will be added to our database columns when the database is created. Required Attribute as name suggests marks the property as required. Also we have a foreign key (AddressId) to an Address table. Let’s look at the Address class now. Address is a simple class with address related properties. One thing to note here is the Persons property. It’s a collection of type Person. This property directly maps to the AddressId foreign key in the Person class and will load all Persons with the same address.

For Entity Framework to map our domain objects to a database table we will create a Data Context called MyDataContext. Notice we specify the DefaultConnection connection string in the constructor. You can turned off Lazy Loading of child properties by setting the LazyLoadingEnabled property, in which case we will explicitly load any child objects as needed instead of EF loading them for us.

Debugging: We can write all sql statements to the Debug window so we can inspect sql sent to Sql Server. This can be very helpful when debugging our code.

Changing Data before Commit: The SaveChangesAction method is called each time data is saved. This lets us modify the data right before it’s saved to the database. In this case we inspect the object and if it’s of type BaseModel we update the Modified date for add and update actions. This pattern can be used to inspect and modify data before it’s committed to the database. After the model and data context is ready you would ideally use code first migrations or a database initializer to have the database created.

Read More:

http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/migrations-and-deployment-with-the-entity-framework-in-an-asp-net-mvc-application

http://www.codeguru.com/csharp/article.php/c19999/Understanding-Database-Initializers-in-Entity-Framework-Code-First.htm

Now that we have our data context and database in place let’s create a data repository that can be used across our application and will encapsulate all our database operations. We are make async database requests by using the async and await keywords, but you may use synchronous calls as well like the Get call. Ideally you would extract the repository into an interface (IBaseRepository) and inject it into all your controllers using an IOC container like Ninject, StructMap, Autofac etc. You would also inject the DataContext into the BaseRepository.

Example using Autofac: Now in my MVC or WebAPi controllers I can simply use the injected repository to perform by database operations on any domain object. Note the data repository methods that take an additional includeProperties parameter. This is used for loading additional child objects within the requested object. So loading the address property along with all Persons with name of Joe would be.

var persons = DataRepository.FindAllBy(p => p.FirstName == "Joe", p => p.Address);

Hope this can serve as a good starting point for anyone who wants to leverage Entity Framework for their .NET projects.

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Great that I found you! For you as for an entrepreneur and for your followers who are probably business owners as well such cloud technology as virtual data rooms may be interesting.

    ReplyDelete