Example #1
0
        /// <summary>
        /// 为实体类型生成一个默认的实体类。
        /// </summary>
        /// <param name="entityType"></param>
        /// <returns></returns>
        private Type GenerateDefaultRepositoryType(Type entityType)
        {
            var baseType = entityType.BaseType;

            //找到继承链条上,最近的一个非泛型父类的仓库类型
            Type baseRepositoryType = null;

            while (baseType != typeof(Entity))
            {
                if (baseType == null)
                {
                    throw new InvalidProgramException("此类并没有继承 Entity 类,不能创建 Repository。");
                }
                if (!baseType.IsGenericType)
                {
                    //不需要为基类创建仓库,这是因为基类声明的仓库类型可能是抽象类型。
                    //var repository = this.FindWithoutLock(baseType);
                    //baseRepositoryType = repository.GetType();

                    var convention = EntityMatrix.FindByEntity(baseType);
                    baseRepositoryType = convention.RepositoryType;
                    break;
                }

                baseType = baseType.BaseType;
            }

            //如果没有,则直接从DefaultEntityRepository上继承。
            if (baseRepositoryType == null)
            {
                baseRepositoryType = typeof(EntityRepository);
            }

            //查找这个类型
            var module    = EmitContext.Instance.GetDynamicModule();
            var className = EntityMatrix.RepositoryFullName(entityType);

            //尝试查找这个类型
            var exsitType = module.GetType(className, false);

            if (exsitType != null)
            {
                return(exsitType);
            }

            //构造一个新的类型。
            var newType = module.DefineType(
                className,
                TypeAttributes.Public | TypeAttributes.Class,
                baseRepositoryType
                );

            return(newType.CreateType());
        }