Skip to main content

Creating common partial class with Entity Framework

When we use the Entity Framework (EF) in multilayer information systems sometimes we want to extend classes generated by EF by adding some common properties or functions. Such operation can`t be conduct on *.edmx data model so we need to make some improvement in our solution. Let`s begin...

Lets assumed that in our soulution we have only three layer (three project):
  1. Client console application which has reference to the second layer  - 'ConsoleApplication' project name
  2. Class library project with class interfaces only - 'Interfaces' project name
  3. Class library class implementation and data model referenced to 'Interfaces' project - 'Classes' project name.
Picture 1. Solution structure.
Now when we have all solution structure we can focus on data model. In the 'Classes' project we create a new folder named 'Model' and inside add new item of ADO.NET Entity Data Model named 'Learning.edmx' - it may be empty or generated from database (in this example I created the empty one). Now it`s time to add some new entities to our model so lets assumed that we want to create a CarBrand entity and a CarModel with one to many relation (i hope You know how to do that). 
Picture 2. Entity data model.
Next step is to create a new folder named 'Objects' (name is not matter) and inside it create two partial classes as presented in the code-sniped below. (For this example I type the class definition in one file but in real project always create separated file for each class!!).

Code Snippet
  1. namespace Classes.Objects
  2. {
  3.     public partial class CarBrand
  4.     {
  5.     }
  7.     public partial class CarModel
  8.     {
  9.     }
  10. }

After complete class implementation we can create an interfaces for each of them. We do this in the 'Interfaces' project.

Code Snippet
  1. namespace Interfaces.IObjects
  2. {
  3.     public interface ICarBrand
  4.     {
  5.         int CarBrandID { get; set; }
  6.         string Name { get; set; }
  7.         IList<ICarModel> CarModels { get; set; }
  8.     }
  10.     public interface ICarModel
  11.     {
  12.         int CarModelID { get; set; }
  13.         string Name { get; set; }
  14.         ICarBrand ParentBrand { get; set; }
  15.     }
  16. }

Please notice that in the line 12 and 19 I added two new properties. First one is list of car models for a single car brand object instance and the second one is parent car brad for car model. Both interfaces as public and  are located in the 'IObject' folder.

Not it`s time to connect interfaces with the class definitions. Because the 'Classes' project has a reference to the 'Interfaces' by using using Interfaces.IObjects we are able to add suitable interface to each class. But it`s end because to connect custom our class to entity generated class we must inherit from special Entity type named EntityObject which is located int System.Data.Objects.DataClasses namespace. So after all changed we already have done out classes presents as follow...

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Interfaces.IObjects;
  6. using System.Data.Objects.DataClasses;
  8. namespace Classes.Objects
  9. {
  10.     public partial class CarBrand : EntityObject, ICarBrand
  11.     {
  12.         public IList<ICarModel> CarModels
  13.         {
  14.             get
  15.             {
  16.                 throw new NotImplementedException();
  17.             }
  18.             set
  19.             {
  20.                 throw new NotImplementedException();
  21.             }
  22.         }
  23.     }
  25.     public partial class CarModel : EntityObject, ICarModel
  26.     {
  27.         public ICarBrand ParentBrand
  28.         {
  29.             get
  30.             {
  31.                 throw new NotImplementedException();
  32.             }
  33.             set
  34.             {
  35.                 throw new NotImplementedException();
  36.             }
  37.         }
  38.     }
  39. }

Notice that we have implement both interfaces but also leave default implementation (line 15 and 33) - we back on it. Now it`s time to make a connection between out classes and classes generated by EF.  After open data model press F4 on empty space and set Namespace property to Classes.Objects (namespace which contains are custom classes). After this do the same after clicking F4 on selected *.edmx file in Solution Explorer - example below. When both task completed just rebuild 'Classes' project.

Picture 3. Setting custom namespace to model.

Now it`s time to make last implementation in out custom class. Please notice that each of out custom class has now a properties defined in data model!! We have to implement two properties ParentBrand in CarModel class and CarModels in CarBrand class. Because out classes (generated by EF and our custom) see each other properties so we can call their own properties as follow.
Code Snippet
  1. namespace Classes.Objects
  2. {
  3.     public partial class CarModel : EntityObject, ICarModel
  4.     {
  5.         public ICarBrand ParentBrand
  6.         {
  7.             get
  8.             {
  9.                 return this.CarBrand as ICarBrand; //conver to Interface
  10.             }
  11.             set
  12.             {
  13.                 this.CarBrand = value as CarBrand; //convert to class
  14.             }
  15.         }
  16.     }
  17.     public partial class CarBrand : EntityObject, ICarBrand
  18.     {
  19.         public IList<ICarModel> CarModels
  20.         {
  21.             get
  22.             {
  23.                 return this.CarModels.Cast<ICarModel>().ToList();
  24.             }
  25.             set
  26.             {
  27.                 this.CarModels = (IList<ICarModel>)value;
  28.             }
  29.         }
  30.     }
  31. }

Now, when our classes are connected to each other we can simple call it`s instance in our Console Application. But to do this we need to create an instance on Model at runtime and create object factory so we implement to in future:) I hope You understood the principle.

Source code

Thank You.

Popular posts from this blog

Autocomplete control with ASP.NET MVC 4 and jQuery

Almost in each modern website project one of the feature is suggesting user possible items to select when he start typing one of them. Such functionality is done by using control named autocomplete . Under the hood  it consists of at least three elements: UI control which allow user to type some text - mainly this in HTML input of text type Server-side function which serves data to be auto-completed Client-side logic (written in JavaScript) which , by using AJAX, send request to the server asynchronously and then process the results. When we think about creating autocomplete control in ASP.NET MVC 4 we definitely should take a look at  jQueryUI framework. One of the feature of this framework is autocomplete control which enables users to quickly find and select from a pre-populated list of values as they type, leveraging searching and filtering. That sounds very good and is excellently what we are looking for. First step in autocomplete control  creation is creating a

Multithread processing of the SqlDataReader - Producer/Consumer design pattern

In today post I want to describe how to optimize usage of a ADO.NET SqlDataReader class by using multi-threading. To present that lets me introduce a problem that I will try to solve.  Scenario : In a project we decided to move all data from a multiple databases to one data warehouse. It will be a good few terabytes of data or even more. Data transfer will be done by using a custom importer program. Problem : After implementing a database agnostic logic of generating and executing a query I realized that I can retrieve data from source databases faster that I can upload them to big data store through HTTP client -importer program. In other words, data reader is capable of reading data faster then I can process it an upload to my big data lake. Solution : As a solution for solving this problem I would like to propose one of a multi-thread design pattern called Producer/Consumer . In general this pattern consists of a two main classes where: Producer class is respons

Full-Text Search with PDF in Microsoft SQL Server

Last week I get interesting task to develop. The task was to search input text in PDF file stored in database as FileStream. The task implementation took me some time so I decided to share it with other developers. Here we are going to use SQL Server 2008 R2 (x64 Developers Edition), external driver from Adobe, Full-Text Search technology and FileStream technology.Because this sems a little bit comlicated let`s make this topic clear and do it step by step. 1) Enable FileStream - this part is pretty easy, just check wheter You already have enabled filestream on Your SQL Server instance - if no simply enable it as in the picture below. Picture 1. Enable filestream in SQL Server instance. 2) Create SQL table to store files  - mainly ther will be PDF file stored but some others is also be allright. Out table DocumentFile will be created in dbo schema and contain one column primary key with default value as sequential GUID. Important this is out table contains FileStream