最近看了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的其余地方