Repository pattern - using EF Fluent API use EntityTypeConfiguration sub-file mapping between configuration Model

EF class EntityTypeConfiguration is a very useful class, in nop to use this class to sub-sub-file configuration file mapping relationship Commerence in Model. Today I will talk about using the Repository pattern implementation example EntityTypeConfiguration in Entity Framework Code First in.

background

To simplify we will only use two tables: Classification Category, product type Product. The final project is structured as follows:

Note: EfRepPatTest.Entity and EfRepPatTest.Data class library project, EfRepPatTest.Implementation a console project. EfRepPatTest.Data project requires a reference to the Entity Framework class library.

BaseEntity.cs

BaseEntity create a base class for all entities, some common properties inside the package.

  1. public class BaseEntity<T>
  2. {
  3. public T Id { get; set; }
  4. }

This means that all entities have a field for the Id, the generic type which can meet all types of situations.

IRepository.cs:

The following defines a generic interface to the IRepository, including a generic add, delete, change.

  1. public interface IRepository<TEntity> where TEntity:class
  2. {
  3. IQueryable<TEntity> GetAll();
  4. TEntity GetById(object id);
  5. void Insert(TEntity entity);
  6. void Update(TEntity entity);
  7. void Delete(TEntity entity);
  8. }

Category.cs:

Entity classes classes

  1. public class Category:BaseEntity<int>
  2. {
  3. public virtual string Name { get; set; }
  4. public List<Product> Products { get; set; }
  5. }

Product.cs:

Physical products category

  1. public class Product:BaseEntity<long>
  2. {
  3. public virtual int CategoryId { get; set; }
  4. public virtual Category Category { get; set; }
  5. public virtual stringName{ get;set;}
  6. public virtual int MinimumStockLevel { get; set; }
  7. }

IDbContext.cs:

Some interfaces IDbContext EF package public interface method.

  1. public interface IDbContext
  2. {
  3. IDbSet<TEntity> Set<TEntity>() where TEntity:class;
  4. int SaveChanges();
  5. void Dispose ();
  6. }

DataContext.cs:

  1. public class DataContext: DbContext,IDbContext
  2. {
  3. public new IDbSet<TEntity> Set<TEntity>() where TEntity : class
  4. {
  5. return base.Set<TEntity>();
  6. }
  7. }

CategoryMap.cs:

Classification map class inherits EntityTypeConfigureation <T>

  1. public class CategoryMap:EntityTypeConfiguration<Category>
  2. {
  3. public CategoryMap()
  4. {
  5. ToTable("Category");
  6. HasKey(c => c.Id).Property(c => c.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
  7. Property(c => c.Name).IsRequired().HasMaxLength(50);
  8. }
  9. }

ProductMap.cs:

Product category mapping class inherits from EntityTypeConfigureation <T>

  1. public class ProductMap:EntityTypeConfiguration<Product>
  2. {
  3. public ProductMap()
  4. {
  5. ToTable("Product");
  6. HasKey(p => p.Id).Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
  7. //CategoryId as foreign key
  8. HasRequired(p => p.Category)
  9. .WithMany(c=>c.Products)
  10. .HasForeignKey(p => p.CategoryId);
  11. Property(p => p.Name).IsRequired().HasMaxLength(100);
  12. Property(p => p.MinimumStockLevel);
  13. }
  14. }

In DataContext class method override OnModelCreating order together with our new EF's Map configuration file, add the following code:

  1. modelBuilder.Configurations.Add(new CategoryMap());
  2. modelBuilder.Configurations.Add(new ProductMap());
  3. base.OnModelCreating(modelBuilder);

The optimization code can look above, may be utilized reflection automatically add the EF Map configuration file as follows:

  1. public class DataContext: DbContext,IDbContext
  2. {
  3. public new IDbSet<TEntity> Set<TEntity>() where TEntity : class
  4. {
  5. return base.Set<TEntity>();
  6. }
  7. protected override void OnModelCreating(DbModelBuilder modelBuilder)
  8. {
  9. var typesToRegister = Assembly.GetExecutingAssembly().GetTypes()
  10. .Where(type => !String.IsNullOrEmpty(type.Namespace))
  11. .Where(type => type.BaseType != null && type.BaseType.IsGenericType &&
  12. type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));
  13. foreach (var type in typesToRegister)
  14. {
  15. dynamicconfigurationInstance = Activator.CreateInstance(type);
  16. modelBuilder.Configurations.Add(configurationInstance);
  17. }
  18. base.OnModelCreating(modelBuilder);
  19. }
  20. }

The advantage is that after the new entity plus EF Map class, without modification DataContext.

RepositoryService.cs:

IRepositroy RepositoryService one particular implementation of the interface, the data access using the EF IDbContext.

  1. public class RepositoryService<TEntity>:IRepository<TEntity> where TEntity:class
  2. {
  3. private IDbContext Context;
  4. private IDbSet<TEntity> Entities
  5. {
  6. get { return this.Context.Set<TEntity>(); }
  7. }
  8. public RepositoryService(IDbContext context)
  9. {
  10. this.Context = context;
  11. }
  12. public IQueryable<TEntity> GetAll()
  13. {
  14. return Entities.AsQueryable();
  15. }
  16. public TEntity GetById(object id)
  17. {
  18. return Entities.Find(id);
  19. }
  20. public void Insert(TEntity entity)
  21. {
  22. Entities.Add(entity);
  23. }
  24. public void Update(TEntity entity)
  25. {
  26. if (entity == null)
  27. throw new ArgumentNullException("entity");
  28. this.Context.SaveChanges();
  29. }
  30. public void Delete(TEntity entity)
  31. {
  32. Entities.Remove(entity);
  33. }
  34. public void Dispose ()
  35. {
  36. Dispose(true);
  37. GC.SuppressFinalize(this);
  38. }
  39. protected virtual void Dispose(bool disposing)
  40. {
  41. if (disposing)
  42. {
  43. if (this.Context != null)
  44. {
  45. this.Context.Dispose();
  46. this.Context = null;
  47. }
  48. }
  49. }
  50. }

Create a new class DataBaseInitializer to initialize the class EF Code First database access.

  1. public class DataBaseInitializer : IDatabaseInitializer<DataContext>
  2. {
  3. public void InitializeDatabase(DataContext context)
  4. {
  5. context.Database.CreateIfNotExists();
  6. }
  7. }

Create a new console application to test the above code Program.cs:

  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. var context = new DataContext();
  6. var dataBaseInitializer = new DataBaseInitializer();
  7. dataBaseInitializer.InitializeDatabase(context);
  8. var categoryRepository = new RepositoryService<Category>(context);
  9. //Adding category in the category entity
  10. var category = new Category ()
  11. {
  12. Name = "Baverage"
  13. };
  14. var products = new List<Product>();
  15. //Adding product in the product entity
  16. var product = new Product()
  17. {
  18. Name = "Soft Drink A",
  19. MinimumStockLevel = 50
  20. };
  21. products.Add(product);
  22. product = new Product()
  23. {
  24. Name = "Soft Drink B",
  25. MinimumStockLevel = 30
  26. };
  27. products.Add(product);
  28. category.Products = products;
  29. //Insert category and save changes
  30. categoryRepository.Insert(category);
  31. context.SaveChanges();
  32. ///////////////////////////////////////////////////////////////////////////////
  33. /////////////////For the next project we shall add Dependency Injection////////
  34. ////////////////But now we have add a Service layer for test manually//////////
  35. ///////////////////////////////////////////////////////////////////////////////
  36. IProductService productRepository = new ProductService();
  37. Console.WriteLine("\n");
  38. Console.WriteLine("Product List:");
  39. Console.WriteLine("-------------------------------------------------");
  40. foreach (var product1 in productRepository.GetAll())
  41. {
  42. Console.WriteLine(string.Format("Product Name : {0}",product1.Name));
  43. if (product1.Id == 9)
  44. {
  45. product1.Name = "Soft Drink AAA";
  46. productRepository.Update(product1);
  47. }
  48. }
  49. Console.WriteLine("Press any key to exit");
  50. Console.ReadKey();
  51. }
  52. }

Add a link to a database in the configuration file.

App.config:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <configuration>
  3. <configSections>
  4. <!-- For more information
  5. on Entity Framework configuration, visit
  6. http://go.microsoft.com/fwlink/?LinkID=237468 -->
  7. <section name="entityFramework"
  8. type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection,
  9. EntityFramework, Version=4.4.0.0, Culture=neutral,
  10. PublicKeyToken=b77a5c561934e089"
  11. requirePermission="false" />
  12. </configSections>
  13. <entityFramework>
  14. <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory,
  15. EntityFramework" />
  16. </entityFramework>
  17. <connectionStrings>
  18. <add name="DataContext"
  19. providerName="System.Data.SqlClient"
  20. connectionString="Data
  21. Source=YourSERVER;Initial Catalog=EfDBExistRepository;Integrated
  22. Security=True;MultipleActiveResultSets=True;"/>
  23. </connectionStrings>
  24. </configuration>

Note: The database link node named "DataContext", and just write our own class "DataContext" the same name. EF framework so you can automatically find this database link information.

Reference: http://www.codeproject.com/Articles/561584/Repository-Pattern-with-Entity-Framework-using

Guess you like

Origin www.cnblogs.com/Jeely/p/10953955.html