如果一个表有几十个字段,写Dto绝对是一个痛不欲生的事情,那么怎么办?用反射吧:
public static string DynamicToClass(object entity, string className) { StringBuilder reval = new StringBuilder(); StringBuilder propertiesValue = new StringBuilder(); var propertiesObj = entity.GetType().GetProperties(); string replaceGuid = Guid.NewGuid().ToString(); foreach (var r in propertiesObj) { propertiesValue.AppendLine(); propertiesValue.AppendFormat("public {0} {1} {2}", r.PropertyType.FullName, r.Name, "{get;set;}"); propertiesValue.AppendLine(); } reval.AppendFormat(@" public class {0}{{ {1} }} ", className, propertiesValue); return reval.ToString(); }
使用:
//通过匿名对象生成实体类 var admin = db.TbAdmin.Find(1); string Viewmodelfromadmin = ClassGenerating.DynamicToClass(dynamicObj, "classDynamic");