最近看了NopCommerce源碼,用core學習着寫了一個項目,修改的地方記錄下。項目地址mysql
NopCommerce框架出來很久了。18年的第一季度 懶加載出來後也會所有移動到.net core。那麼就更好玩了。git
項目內容github
固然NopCommerce還包含不少特技:Plugin,Seo,訂閱發佈,theme切換等等。這些後期再維護進去。web
項目介紹sql
Nop.Core:【核心層】基礎設施,例:領域對象,倉庫接口,引擎接口,DI管理接口,反射,公共方法。數據庫
Nop.Data:【數據層】EF相關,dbcontext,倉儲實現,mappingjson
Nop.Services:【服務層】數據邏輯處理由這層提供。app
Nop.Web:【頁面層】展現界面。框架
Nop.Web.Framework:【頁面基礎層】web層的上層封裝。例如啓動項的實現,DI實現。ide
詳細的分層思想和細節這裏再也不復述。
2.項目修改點
EF6轉換到EFCore,數據庫選擇mysql,動態加載dbset 看了相關代碼,在進行解釋
1 public class DataBaseStartup: ISelfStartup 2 { 3 4 public void ConfigureServices(IServiceCollection services, IConfigurationRoot configuration) 5 { 6 services.AddDbContext<SelfDbContext>(x => x.UseMySql(configuration.GetConnectionString("MySql"))); 7 } 8 9 public void Configure(IApplicationBuilder application) 10 { 11 var dbContext=EngineContext.Current.ServiceProvider.GetService<SelfDbContext>(); 12 dbContext.Database.EnsureCreated(); 13 } 14 15 public int Order { get; } = 1; 16 }
public SelfDbContext(DbContextOptions options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.AddEntityConfigurationsFromAssembly(GetType().Assembly); base.OnModelCreating(modelBuilder); }
1 public static class ModelBuilderExtenions 2 { 3 private static IEnumerable<Type> GetMappingTypes(this Assembly assembly, Type mappingInterface) 4 { 5 return assembly.GetTypes().Where(x => !x.IsAbstract && !x.IsGenericType && !x.IsInterface && x.GetInterfaces().Any(y => y == mappingInterface)); 6 } 7 8 public static void AddEntityConfigurationsFromAssembly(this ModelBuilder modelBuilder, Assembly assembly) 9 { 10 var mappingTypes = assembly.GetMappingTypes(typeof(ISelfEntityMappingConfiguration)); 11 foreach (var config in mappingTypes.Select(Activator.CreateInstance).Cast<ISelfEntityMappingConfiguration>()) 12 { 13 config.Map(modelBuilder); 14 } 15 } 16 }
1 public class StudentMapping : ISelfEntityMappingConfiguration 2 { 3 public void Map(ModelBuilder b) 4 { 5 b.Entity<Student>().ToTable("Student") 6 .HasKey(p => p.Id); 7 8 b.Entity<Student>().Property(p => p.Class).HasMaxLength(50).IsRequired(); 9 b.Entity<Student>().Property(p => p.Name).HasMaxLength(50); 10 } 11 }
1 public interface ISelfEntityMappingConfiguration 2 { 3 void Map(ModelBuilder b); 4 }
1 public class Student:BaseEntity 2 { 3 public string Name { get; set; } 4 5 public string Class { get; set; } 6 }
解釋:
3.項目繼承nopcommerce的其餘地方