public static Type Build(TypeMeta meta) {//需增加一个判断 TypeBuilder builder = moduleBuilder.DefineType(meta.TypeName, TypeAttributes.Public); CustomAttributeBuilder tableAttributeBuilder = new CustomAttributeBuilder(typeof(TableAttribute).GetConstructor(new Type[1] { typeof(string) }), new object[] { "RuntimeModel_" + meta.TypeName }); builder.SetParent(meta.BaseType); builder.SetCustomAttribute(tableAttributeBuilder); foreach (var item in meta.PropertyMetas) { AddProperty(item, builder, meta.BaseType); } return(builder.CreateTypeInfo().UnderlyingSystemType); }
//这个方法就是把一个RuntimeModelMeta转换成更接近类结构的TypeMeta对象 private TypeMeta GetTypeMetaFromModelMeta(RuntimeModelMeta meta) { TypeMeta typeMeta = new TypeMeta(); //我们让所有的动态类型都继承自DynamicEntity类,这个类主要是为了方便属性数据的读取,具体代码看后面 typeMeta.BaseType = typeof(DynamicEntity); typeMeta.TypeName = meta.ClassName; foreach (var item in meta.ModelProperties) { TypeMeta.TypePropertyMeta pmeta = new TypeMeta.TypePropertyMeta(); pmeta.PropertyName = item.PropertyName; //如果必须输入数据,我们在属性上增加RequireAttribute特性,这样方便我们进行数据验证 if (item.IsRequired) { TypeMeta.AttributeMeta am = new TypeMeta.AttributeMeta(); am.AttributeType = typeof(RequiredAttribute); am.Properties = new string[] { "ErrorMessage" }; am.PropertyValues = new object[] { "请输入" + item.Name }; pmeta.AttributeMetas.Add(am); } if (item.ValueType == "string") { pmeta.PropertyType = typeof(string); TypeMeta.AttributeMeta am = new TypeMeta.AttributeMeta(); //增加长度验证特性 am.AttributeType = typeof(StringLengthAttribute); am.ConstructorArgTypes = new Type[] { typeof(int) }; am.ConstructorArgValues = new object[] { item.Length }; am.Properties = new string[] { "ErrorMessage" }; am.PropertyValues = new object[] { item.Name + "长度不能超过" + item.Length.ToString() + "个字符" }; pmeta.AttributeMetas.Add(am); } else if (item.ValueType == "int") { if (!item.IsRequired) { pmeta.PropertyType = typeof(int?); } else { pmeta.PropertyType = typeof(int); } } else if (item.ValueType == "datetime") { if (!item.IsRequired) { pmeta.PropertyType = typeof(DateTime?); } else { pmeta.PropertyType = typeof(DateTime); } } else if (item.ValueType == "bool") { if (!item.IsRequired) { pmeta.PropertyType = typeof(bool?); } else { pmeta.PropertyType = typeof(bool); } } typeMeta.PropertyMetas.Add(pmeta); } return(typeMeta); }