NopCommerce Architecture Analysis of 3 EntityFramework Database Preliminary Test and Data Operation

  • 2021-07-16 02:16:03
  • OfStack

System startup tasks: IStartupTask, startup tasks are mainly the initialization and loading of the database.

IStartupTask calls IEfDataProvider to initialize the database.

IEfDataProvider, SqlCeDataProvider: Get data connection factory, different type of database, different connection factory.

The entity class EfStartUpTask of interface IStartupTask is implemented as follows:


public class EfStartUpTask : IStartupTask 
{ 
 public void Execute() 
 { 
  var settings = EngineContext.Current.Resolve<DataSettings>(); 
  if (settings != null && settings.IsValid()) 
  { 
   var provider = EngineContext.Current.Resolve<IEfDataProvider>(); 
   if (provider == null) 
    throw new NopException("No EfDataProvider found"); 
   provider.SetDatabaseInitializer(); 
  } 
 } 

 public int Order 
 { 
  //ensure that this task is run first 
  get { return -1000; } 
 } 
}

SqlCeInitializer, CreateCeDatabaseIfNotExists initialize the database.

IDbContext, NopObjectContext System Database Operation Context. Load all database mapping classes: EntityTypeConfiguration < TEntityType > . The code is as follows:


protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
 //dynamically load all configuration 
 //System.Type configType = typeof(LanguageMap); //any of your configuration classes here 
 //var typesToRegister = Assembly.GetAssembly(configType).GetTypes() 

 var typesToRegister = Assembly.GetExecutingAssembly().GetTypes() 
 .Where(type => !String.IsNullOrEmpty(type.Namespace)) 
 .Where(type => type.BaseType != null && type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>)); 
 foreach (var type in typesToRegister) 
 { 
 dynamic configurationInstance = Activator.CreateInstance(type); 
 modelBuilder.Configurations.Add(configurationInstance); 
 } 
 //...or do it manually below. For example, 
 //modelBuilder.Configurations.Add(new LanguageMap()); 



 base.OnModelCreating(modelBuilder); 
} 

This method is inherited from DbContext. And when the system starts, it is called to establish the corresponding relationship between data table and entity.

In the type dependency registration class Nop. Web. Framework. DependencyRegistrar, the database factory is created and the database is loaded. The following code:


//data layer 
var dataSettingsManager = new DataSettingsManager(); 
var dataProviderSettings = dataSettingsManager.LoadSettings(); 
builder.Register(c => dataSettingsManager.LoadSettings()).As<DataSettings>(); 
builder.Register(x => new EfDataProviderManager(x.Resolve<DataSettings>())).As<BaseDataProviderManager>().InstancePerDependency(); 


builder.Register(x => (IEfDataProvider)x.Resolve<BaseDataProviderManager>().LoadDataProvider()).As<IDataProvider>().InstancePerDependency(); 
builder.Register(x => (IEfDataProvider)x.Resolve<BaseDataProviderManager>().LoadDataProvider()).As<IEfDataProvider>().InstancePerDependency(); 

if (dataProviderSettings != null && dataProviderSettings.IsValid()) 
{ 
 var efDataProviderManager = new EfDataProviderManager(dataSettingsManager.LoadSettings()); 
 var dataProvider = (IEfDataProvider)efDataProviderManager.LoadDataProvider(); 
 dataProvider.InitConnectionFactory(); 

 builder.Register<IDbContext>(c => new NopObjectContext(dataProviderSettings.DataConnectionString)).InstancePerHttpRequest(); 
} 
else 
{ 
 builder.Register<IDbContext>(c => new NopObjectContext(dataSettingsManager.LoadSettings().DataConnectionString)).InstancePerHttpRequest(); 
} 


builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>)).InstancePerHttpRequest(); 

The database initialization method of entity class SqlServerDataProvider of interface IEfDataProvider is as follows:


/// <summary> 
/// Set database initializer 
/// </summary> 
public override void SetDatabaseInitializer() 
{ 
 //pass some table names to ensure that we have nopCommerce 2.X installed 
 var tablesToValidate = new[] {"Customer", "Discount", "Order", "Product", "ShoppingCartItem"}; 

 //custom commands (stored proedures, indexes) 

 var customCommands = new List<string>(); 
 //use webHelper.MapPath instead of HostingEnvironment.MapPath which is not available in unit tests 
 customCommands.AddRange(ParseCommands(HostingEnvironment.MapPath("~/App_Data/SqlServer.Indexes.sql"), false)); 
 //use webHelper.MapPath instead of HostingEnvironment.MapPath which is not available in unit tests 
 customCommands.AddRange(ParseCommands(HostingEnvironment.MapPath("~/App_Data/SqlServer.StoredProcedures.sql"), false)); 
 
 var initializer = new CreateTablesIfNotExist<NopObjectContext>(tablesToValidate, customCommands.ToArray()); 
 Database.SetInitializer(initializer); 
} 

In addition, EntityFramework is an ORM framework, which establishes the connection with the database and the corresponding Guangxi of entities and data tables through the database access context. And by creating IRepository < T > Generic entity class to implement the processing of each kind of data, which is called Dao layer. The business logic layer accesses the warehouse Repository through the data of each entity < T > To perform database operations.


Related articles: