You can download the source code here.
Now lets create Repository classes and DataContext class. For this we need to install EntityFramework package using nuget.
Open Package Manager Console from Tools -> Nuget Package Manager and issue below command in console.
1 |
install-package EntityFramework |
The structure of this project is as below. Configuration folder contains configuration settings for each model.Repository folder contains interfaces and implementation for each repository. Here one model is mapped to one repository.
Create an abstract BaseRepository class at the project root. This base class is inherited by all repository classes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
public abstract class BaseRepository { private readonly DbContext _dataContext; protected BaseRepository(DbContext dataContext) { _dataContext = dataContext; } public string SaveChanges() { var errMsg = string.Empty; try { var result = _dataContext.SaveChanges(); if (result > 0) { return "Success"; } } catch (DbEntityValidationException dbEx) { errMsg = dbEx.EntityValidationErrors.Aggregate(errMsg, (current1, validationErrors) => validationErrors.ValidationErrors.Aggregate(current1, (current, validationError) => current + string.Format("Field: {0}, Error: {1}", validationError.PropertyName, validationError.ErrorMessage))); } catch (DbUpdateException dbUpdateExceptionEx) { var err = dbUpdateExceptionEx.InnerException.InnerException.Message; errMsg = err.Replace("\r\n", "").Replace("The statement has been terminated.", ""); } return errMsg; } } |
Create an abstract BasicEntityConfiguration class in the project root. This contains column level constraints for properties in BaseEntity.
1 2 3 4 5 6 7 8 9 10 11 12 |
public abstract class BasicEntityConfiguration<TEntity> : EntityTypeConfiguration<TEntity> where TEntity : BaseEntity { public BasicEntityConfiguration() { Property(p => p.CreatedDate).HasColumnName("CREATED_DATE").IsRequired(); Property(p => p.CreatedBy).HasColumnName("CREATED_BY").HasMaxLength(50).IsRequired(); Property(p => p.ModifiedDate).HasColumnName("MODIFIED_DATE").IsRequired(); Property(p => p.ModifiedBy).HasColumnName("MODIFIED_BY").HasMaxLength(50).IsRequired(); Property(p => p.IsDeleted).HasColumnName("IS_DELETED").IsRequired(); Property(e => e.RecordTimeStamp).HasColumnName("RTS").IsRowVersion().IsRequired(); } } |
Add EmployeeConfiguration class to Employee -> Configuration folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class EmployeeConfiguration<TEntity> : BasicEntityConfiguration<EmployeeEntity> { public EmployeeConfiguration() { ToTable("Employee", "COD"); Property(p => p.Id).HasColumnName("EMPLOYEE_ID"); Property(p => p.FirstName).HasColumnName("FIRST_NAME").HasMaxLength(200).IsRequired(); Property(p => p.LastName).HasColumnName("LAST_NAME").HasMaxLength(200).IsRequired(); Property(p => p.Address).HasColumnName("ADDRESS").HasMaxLength(200); Property(p => p.City).HasColumnName("CITY").HasMaxLength(200); Property(p => p.Country).HasColumnName("COUNTRY").HasMaxLength(200); } } |
Add OrderConfiguration class in Order-> Configuration folder.
1 2 3 4 5 6 7 8 9 10 11 12 |
public class OrderConfiguration<TEntity> : BasicEntityConfiguration<OrderEntity> { public OrderConfiguration() { ToTable("Order", "COD"); Property(p => p.Id).HasColumnName("ORDER_ID"); Property(p => p.EmployeeId).HasColumnName("EMPLOYEE_ID"); Property(p => p.RequiredDate).HasColumnName("REQUIRED_DATE"); Property(p => p.ShipAddress).HasColumnName("SHIP_ADDRESS"); } } |
Add ProductConfiguration class in Product-> Configuration folder.
1 2 3 4 5 6 7 8 9 10 11 |
public class ProductConfiguration<TEntity> : BasicEntityConfiguration<ProductEntity> { public ProductConfiguration() { ToTable("Product", "COD"); Property(p => p.Id).HasColumnName("PRODUCT_ID"); Property(p => p.ProductName).HasColumnName("PRODUCT_NAME").HasMaxLength(200).IsRequired(); Property(p => p.UnitPrice).HasColumnName("UNIT_PRICE"); } } |
Add OrderDetailsConfiguration in Order -> Configuration.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class OrderDetailsConfiguration<TEntity> : BasicEntityConfiguration<OrderDetailsEntity> { public OrderDetailsConfiguration() { ToTable("OrderDetails", "COD"); Property(p => p.Id).HasColumnName("ORDER_DETAILS_ID"); Property(p => p.OrderId).HasColumnName("ORDER_ID"); Property(p => p.ProductId).HasColumnName("PRODUCT_ID"); Property(p => p.UnitPrice).HasColumnName("UNIT_PRICE"); Property(p => p.Quantity).HasColumnName("QUANTITY"); Property(p => p.Discount).HasColumnName("DISCOUNT"); } } |
Create IEmployeeRepository in Employee-> Repository -> Interface folder.
Create IOrderRepository, IOrderDetailsRepository in Order -> Repository -> Interface folder.
Create IProductRepository in Product -> Repository -> Interface folder.
Add below code in IEmployeeRepository.
1 2 3 4 5 6 7 |
public interface IEmployeeRepository { void AddEmployee(EmployeeEntity employeeEntity); List<EmployeeEntity> GetAllEmployees(); EmployeeEntity GetEmployeeById(int employeeId); string SaveChanges(); } |
Create EmployeeRepository class in Employee -> Repository folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
public class EmployeeRepository : BaseRepository, IEmployeeRepository { private readonly DbContext _dataContext; public EmployeeRepository(DbContext dataContext) : base(dataContext) { _dataContext = dataContext; } public void AddEmployee(EmployeeEntity employeeEntity) { if (employeeEntity == null) { throw new ArgumentNullException("employeeEntity"); } var set = _dataContext.Set<EmployeeEntity>(); set.Add(employeeEntity); } public List<EmployeeEntity> GetAllEmployees() { return _dataContext.Set<EmployeeEntity>().Where(x => !x.IsDeleted).ToList(); } public EmployeeEntity GetEmployeeById(int employeeId) { return _dataContext.Set<EmployeeEntity>().FirstOrDefault(x => x.Id.Equals(employeeId)); } } |
And finally lets create the DataContext class. Add a class file for CodifyDataContext and add below code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
using Codify.DataAccess.Employee.Configuration; using Codify.DataAccess.Order.Configuration; using Codify.DataAccess.Product.Configuration; using Codify.Entity.Employee; using Codify.Entity.Order; using Codify.Entity.Product; using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; namespace Codify.DataAccess { public class CodifyDataContext : DbContext { public CodifyDataContext() : base("name = CodifyDataContext") { } public DbSet<EmployeeEntity> employees { get; set; } public DbSet<ProductEntity> products { get; set; } public DbSet<OrderEntity> orders { get; set; } public DbSet<OrderDetailsEntity> orderDetails { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); modelBuilder.Configurations.Add(new EmployeeConfiguration<EmployeeEntity>()); modelBuilder.Configurations.Add(new ProductConfiguration<ProductEntity>()); modelBuilder.Configurations.Add(new OrderConfiguration<OrderEntity>()); modelBuilder.Configurations.Add(new OrderDetailsConfiguration<OrderDetailsEntity>()); base.OnModelCreating(modelBuilder); } } } |
Create a new console project Codify.TestConsole to test the code and insert a few data into employee table. Below is the content in the Program.cs file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
class Program { static CodifyDataContext codifyDataContext = new CodifyDataContext(); static void Main(string[] args) { CreateEmployee_1(); CreateEmployee_2(); Console.ReadKey(); } private static void CreateEmployee_1() { EmployeeEntity employee = new EmployeeEntity(); employee.City = "Bangalore"; employee.Country = "India"; employee.FirstName = "Sameer"; employee.LastName = "Mohammadali"; employee.CreatedBy = System.Environment.UserName; employee.ModifiedBy = System.Environment.UserName; employee.CreatedDate = DateTime.Now; employee.ModifiedDate = DateTime.Now; IEmployeeRepository roleRepository = new EmployeeRepository(codifyDataContext); roleRepository.AddEmployee(employee); string message = roleRepository.SaveChanges(); Console.WriteLine(message); } private static void CreateEmployee_2() { EmployeeEntity employee = new EmployeeEntity(); employee.City = "Bangalore"; employee.Country = "India"; employee.FirstName = "Haris"; employee.LastName = "K M"; employee.CreatedBy = System.Environment.UserName; employee.ModifiedBy = System.Environment.UserName; employee.CreatedDate = DateTime.Now; employee.ModifiedDate = DateTime.Now; IEmployeeRepository roleRepository = new EmployeeRepository(codifyDataContext); roleRepository.AddEmployee(employee); string message = roleRepository.SaveChanges(); Console.WriteLine(message); } } |
Install EntityFramework in the TestConsole project.
Edit App.config and add the connection string to the database.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </configSections> <connectionStrings> <add name="CodifyDataContext" connectionString="Data Source=LIN35005716\SQLEXPRESS;Initial Catalog=Codify;Integrated Security=True" providerName="System.Data.SqlClient" /> </connectionStrings> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" /> </startup> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> <providers> <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> </providers> </entityFramework> </configuration> |
Now run the console application and database will be created by the entity framework.
One comment on “Entity Framework Repository Pattern Demo Application – Part 2”