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.     }
  6.  
  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.     }
  9.  
  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;
  7.  
  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.     }
  24.  
  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

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

Playing with a .NET types definition

In the last few days I spent some time trying to unify structure of one of the project I`m currently working on. Most of the changes were about changing variable types because it`s were not used right way. That is why in this post I want to share my observations and practices with you. First of all we need to understand what ' variable definition ' is and how it`s different from ' variable initialization '. This part should be pretty straightforward:   variable definition  consist of data type and variable name only <data_type> <variable_name> ; for example int i ; . It`s important to understand how variable definition affects your code because it behaves differently depends weather you work with value or reference types. In the case of value types after defining variable it always has default value and it`s never null value. However after defined reference type variable without initializing it has null value by default. variable initialization  is

Persisting Enum in database with Entity Framework

Problem statement We all want to write clean code and follow best coding practices. This all engineers 'North Star' goal which in many cases can not be easily achievable because of many potential difficulties with converting our ideas/good practices into working solutions.  One of an example I recently came across was about using ASP.NET Core and Entity Framework 5 to store Enum values in a relational database (like Azure SQL). Why is this a problem you might ask... and my answer here is that you want to work with Enum types in your code but persist an integer in your databases. You can think about in that way. Why we use data types at all when everything could be just a string which is getting converted into a desirable type when needed. This 'all-string' approach is of course a huge anti-pattern and a bad practice for many reasons with few being: degraded performance, increased storage space, increased code duplication.  Pre-requirements 1. Status enum type definition