续上篇:
DBContext
在上篇 图一类库根目录创建的 DbContextBase
////// 数据库上下文基类 /// ///实现了DbContext对象的上下文对象 public class DbContextBase: DbContext { #region ctor public DbContextBase() : base(GetConnectionString()) { } public DbContextBase(string nameOrConnectionString) : base(GetConnectionString()) { } #endregion #region 获取数据库连接对象 private static string GetConnectionString() { string dbConnectionName = "Innovatordb"; ConnectionStringSettings connectionStringSettings = ConfigurationManager.ConnectionStrings[dbConnectionName]; if (null == connectionStringSettings) { throw new InvalidOperationException("请配置数据库连接字符串,连接名称{0}".FormatWith(dbConnectionName)); } return connectionStringSettings.ConnectionString; } #endregion protected override void OnModelCreating(DbModelBuilder modelBuilder) { //移除一对多级联删除 modelBuilder.Conventions.Remove(); //注册实体配置信息 IEntityMapper[] entityMappers = InitialEntityMapper.Initial; foreach (IEntityMapper mapper in entityMappers) { mapper.RegistTo(modelBuilder.Configurations); } } }
用于上下文对象的初始化,
此处出现了一个IEntityMapper的接口对象,,,,,这个稍后单独说下,还是出自O#,只不过现在的3.x版本的O#锋哥分的比较细,一时间不容易看清,所以稍后我从当初最基本的实现方式说。目的是将实体对象映射到上下文,见下方类定义(同样在上篇 图一的根目录)
映射步骤一:
EntityTypeConfiguration对该对象的继承,用于创建Mapping表关联以及表单字段属性时候使用。
////// 数据实体映射配置基类 /// ///动态实体类型 ///动态主键类型 public abstract class EntityConfigurationBase: EntityTypeConfiguration , IEntityMapper where TEntity : class { /// /// 获取 相关上下文类型,如为null,将使用默认上下文,否则使用指定的上下文类型 /// public virtual Type DbContextType { get { return null; } } ////// 将当前实体映射对象注册到当前数据访问上下文实体映射配置注册器中 /// /// 实体映射配置注册器 public void RegistTo(ConfigurationRegistrar configurations) { configurations.Add(this); } }
步骤二:(上篇 图一的根目录创建以下两个类)
////// 实体映射接口 /// public interface IEntityMapper { ////// 将当前实体映射对象注册到当前数据访问上下文实体映射配置注册器中 /// /// 实体映射配置注册器 void RegistTo(ConfigurationRegistrar configurations); }
////// 初始化实体对象 /// public static class InitialEntityMapper { #region Initialize database entity mapper Collection object private static readonly ICollection_mapperAssemblies = new List ();//用于存放mapper对象 /// /// 加载实体映射对象程序集到集合-在Global中初始化 /// /// //public static void AddMapperAssembly(Assembly assembly) public static void InitialMapperAssembly(Assembly assembly) { if (assembly != null) { if (_mapperAssemblies.Any(a => a == assembly)) return; _mapperAssemblies.Add(assembly); } } ////// 初始化实体属性-外部调用 /// public static IEntityMapper[] Initial { get { return EntityMappers(); } } ////// 初始化Mapper对象 调用对象 OnModelCreating /// ///private static IEntityMapper[] EntityMappers() { try { Type baseType = typeof(IEntityMapper); Type[] mapperTypes = _mapperAssemblies.SelectMany(assembly => assembly.GetTypes()) .Where(type => baseType.IsAssignableFrom(type) && type != baseType && !type.IsAbstract).ToArray(); IEntityMapper[] result = mapperTypes.Select(type => Activator.CreateInstance(type) as IEntityMapper) .ToArray(); return result; } catch (Exception ex) { throw new Exception(ex.Message); } } #endregion }
至此,上下文对象初始化完毕,同时,实体的映射基本方法创建完成,可实现上下文实体对象的自动映射。
各段代码注释 写的也很清楚。