private void SetupEntity(bool includeComments, ExtendedPropertyCommentsStyle includeExtendedPropertyComments) { string comments; if (includeComments) { comments = " // " + Name; if (IsPrimaryKey) { if (IsPrimaryKeyViaUniqueIndex) { comments += " (Primary key via unique index " + UniqueIndexName + ")"; } else { comments += " (Primary key)"; } } } else { comments = string.Empty; } if (includeExtendedPropertyComments == ExtendedPropertyCommentsStyle.AtEndOfField && !string.IsNullOrEmpty(ExtendedProperty)) { if (string.IsNullOrEmpty(comments)) { comments = " // " + ExtendedProperty; } else { comments += ". " + ExtendedProperty; } } if (IsPrimaryKey) { StringBuilder build = new StringBuilder(); build.AppendLine(string.Format("private {0} {1} _{2};", PropertyType, CodeFirstTools.CheckNullable(this), PropertyNameHumanCase.ToLower())); build.AppendLine(string.Format("public {0} {1} {2} {3} {4}", PropertyType, CodeFirstTools.CheckNullable(this), PropertyName, "{ get { return _" + PropertyNameHumanCase.ToLower() + " ; } set { this.Id = value; this._" + PropertyNameHumanCase.ToLower() + " = value; }}", comments)); Entity = build.ToString(); } else { Entity = string.Format("public {0}{1} {2} {3}{4}", PropertyType, CodeFirstTools.CheckNullable(this), PropertyName, IsStoreGenerated ? "{ get; internal set; }" : "{ get; set; }", comments); } }
/// <summary> /// 添加构架应用程序 /// </summary> /// <param name="ProjectCommon"></param> private void NewProject() { try { bool allowNew = true; bool isPartService = KeywordContainer.Resove("$IsPartService$") == "true"; GenerateContext context = new GenerateContext(); context.GeneratedOne += context_GeneratedOne; CodeGenerate generateCode = new CodeGenerate(); TempGenerate generateTemp = new TempGenerate(); generateTemp.TempBuild = new StringBuilder(); generateTemp.TemplateName = "$DBContextContent$"; TempGenerate generateProTemp = new TempGenerate(); generateProTemp.TempBuild = new StringBuilder(); generateProTemp.TemplateName = "$ProfileContent$"; TempGenerate serverProTemp = new TempGenerate(); serverProTemp.TempBuild = new StringBuilder(); serverProTemp.TemplateName = "$ServiceContent$"; TempGenerate iServerProTemp = new TempGenerate(); iServerProTemp.TempBuild = new StringBuilder(); iServerProTemp.TemplateName = "$IServiceContent$"; TempGenerate containerTemp = new TempGenerate(); containerTemp.TempBuild = new StringBuilder(); containerTemp.TemplateName = "$ContainerContent$"; Dictionary <string, string> container = new Dictionary <string, string>(); string str = string.Empty; if (CodeFirstTools.DataType == "MicrosoftSqlServer") { str = "<add name=\"" + CodeFirstTools.DbContextName + "\" providerName=\"" + CodeFirstTools.ProviderName + "\" connectionString=\"" + CodeFirstTools.ConnectionString + ";MultipleActiveResultSets=True;Pooling=True;\"/>"; } else { str = "<add name=\"" + CodeFirstTools.DbContextName + "\" providerName=\"Oracle.DataAccess.Client\" connectionString=\"" + CodeFirstTools.ConnectionString + "\"/>"; } int totalPercent = CodeFirstLogic.Tables.Count; #region 循环实体 _processCurrentCount = 0; _processTotalCount = CodeFirstLogic.Tables.Count; _totalPercent = 0.6f; //循环实体 foreach (Table tbl in CodeFirstLogic.Tables.Where(t => !t.IsMapping).OrderBy(x => x.NameHumanCase)) { _processCurrentCount++; Dictionary <string, string> keycontainer = new Dictionary <string, string>(); keycontainer.Add("$Entity$", tbl.Name); keycontainer.Add("$Data2Obj$", tbl.NameHumanCase); keycontainer.Add("$Schema$", tbl.Schema); keycontainer.Add("$MapPrimaryKey$", tbl.PrimaryKeyNameHumanCase()); string xmlPath = Path.Combine(CommonContainer.SolutionPath, CommonContainer.xmlName); xmlManager.WriteEntity(tbl.Name, tbl.NameHumanCase, xmlPath); StringBuilder build = new StringBuilder(); StringBuilder entityBuild = new StringBuilder(); StringBuilder dtoBuild = new StringBuilder(); //主键 foreach (Column col in tbl.Columns.Where(x => !x.Hidden).OrderBy(x => x.Ordinal)) { build.AppendLine(col.Config); entityBuild.AppendLine(" " + CodeFirstLogic.WritePocoColumn(col)); dtoBuild.AppendLine(" [DataMember]"); dtoBuild.AppendLine(string.Format(" public {0}{1} {2} {3}", col.PropertyType, CodeFirstTools.CheckNullable(col), col.PropertyName, "{get; set; }")); } keycontainer.Add("$MapProperty$", build.ToString()); keycontainer.Add("$Property$", entityBuild.ToString()); keycontainer.Add("$Data2ObjContent$", dtoBuild.ToString()); build.Clear(); entityBuild.Clear(); dtoBuild.Clear(); //外键 if (tbl.HasForeignKey) { foreach (Column col in from c in tbl.Columns.OrderBy(x => x.Ordinal) where c.ConfigFk != null select c) { build.AppendLine(col.ConfigFk); } foreach (Column col in from c in tbl.Columns.OrderBy(x => x.EntityFk) where c.EntityFk != null select c) { entityBuild.AppendLine(" " + col.EntityFk); } } keycontainer.Add("$MapForeignKey$", build.ToString()); keycontainer.Add("$ForeignKey$", entityBuild.ToString()); build.Clear(); entityBuild.Clear(); //导航属性 if (tbl.ReverseNavigationProperty.Count() > 0) { foreach (string s in tbl.ReverseNavigationProperty.OrderBy(x => x)) { entityBuild.AppendLine(" " + s); } } keycontainer.Add("$Navigation$", entityBuild.ToString()); entityBuild.Clear(); //构造函数 if (tbl.Columns.Where(c => c.Default != string.Empty).Count() > 0 || tbl.ReverseNavigationCtor.Count() > 0) { entityBuild.AppendLine(" public " + tbl.Name + "()"); entityBuild.AppendLine(" {"); foreach (Column col in tbl.Columns.OrderBy(x => x.Ordinal).Where(c => c.Default != string.Empty)) { entityBuild.AppendLine(" " + col.PropertyName + "=" + col.Default + ";"); } foreach (string s in tbl.ReverseNavigationCtor) { entityBuild.AppendLine(" " + s); } entityBuild.AppendLine(" }"); } keycontainer.Add("$Constructor$", entityBuild.ToString()); entityBuild.Clear(); context.injection(generateCode, CdeCmdId.DomainContextId.IRepository, allowNew, keycontainer); //IRepository context.injection(generateCode, CdeCmdId.InfrastructureId.Repository, allowNew, keycontainer); //Repositor context.injection(generateCode, CdeCmdId.ApplicationId.Application, allowNew, keycontainer); //Application context.injection(generateCode, CdeCmdId.IApplicationId.IApplication, allowNew, keycontainer); //IApplication context.injection(generateCode, CdeCmdId.Data2ObjectId.Data2Obj, allowNew, keycontainer); //Data2Obj context.injection(generateCode, CdeCmdId.InfrastructureId.Map, allowNew, keycontainer); //Map context.injection(generateCode, CdeCmdId.DomainEntityId.Entity, allowNew, keycontainer); //Entity context.injection(generateProTemp, CdeCmdId.Data2ObjectId.Profile.UnFix, _processCurrentCount == CodeFirstLogic.Tables.Count, keycontainer); //ProfiTemp context.injection(generateTemp, CdeCmdId.InfrastructureId.DBContext.UnFix, _processCurrentCount == CodeFirstLogic.Tables.Count, keycontainer); //DbContextTemp context.injection(serverProTemp, CdeCmdId.ServiceId.Service.UnFix, isPartService || _processCurrentCount == CodeFirstLogic.Tables.Count, keycontainer); //ServerTemp context.injection(iServerProTemp, CdeCmdId.ServiceId.IService.UnFix, isPartService || _processCurrentCount == CodeFirstLogic.Tables.Count, keycontainer); //IServerTemp if (isPartService) { keycontainer.Add("$ServiceName$", tbl.NameHumanCase); context.injection(generateCode, CdeCmdId.ServiceId.IService.Fix, allowNew, keycontainer); //IServer context.injection(generateCode, CdeCmdId.ServiceId.CodeBehind, allowNew, keycontainer); //CodeBehind context.injection(generateCode, CdeCmdId.ServiceId.Service.Fix, allowNew, keycontainer); //Server } context.injection(containerTemp, CdeCmdId.ServiceId.Container.UnFix, _processCurrentCount == CodeFirstLogic.Tables.Count, keycontainer); //ContainerTemp _currentTotalCount = context.Count; context.Commit(); } container.Add("$ConnectionString$", str); container.Add("$DBSchemaApp$", string.Format("<add key=\"DBSchema\" value=\"{0}\"/>", CodeFirstTools.SchemaName)); #endregion context.injection(generateCode, CdeCmdId.InfrastructureId.DbContextExtensions, allowNew, container); //DbContextExtensions context.injection(generateCode, CdeCmdId.InfrastructureId.DBContext.Fix, allowNew, null); //DbContext context.injection(generateCode, CdeCmdId.Data2ObjectId.Profile.Fix, allowNew, null); //DbContext context.injection(generateCode, CdeCmdId.InfrastructureId.ContextUnit, allowNew, null); //DbContextUnit if (!isPartService) { container.Add("$ServiceName$", KeywordContainer.Resove("$ProjectName$")); context.injection(generateCode, CdeCmdId.ServiceId.IService.Fix, allowNew, container); //IServer context.injection(generateCode, CdeCmdId.ServiceId.CodeBehind, allowNew, container); //CodeBehind context.injection(generateCode, CdeCmdId.ServiceId.Service.Fix, allowNew, container); //Server } context.injection(generateCode, CdeCmdId.ServiceId.Container.Fix, allowNew, null); //Container context.injection(generateCode, CdeCmdId.ServiceId.WebConfig, allowNew, null); //WebConfig context.injection(generateCode, CdeCmdId.ServiceId.UnityInstanceProviderServiceBehavior, allowNew, null); //UnityInstanceProviderServiceBehavior context.injection(generateCode, CdeCmdId.ServiceId.UnityInstanceProvider, allowNew, null); //UnityInstanceProvider context.injection(generateCode, CdeCmdId.ServiceId.AttachDataSignBehavior, allowNew, null); //AttachDataSignBehavior , _totalPercent = 0.8f; _processTotalCount = 1; _processCurrentCount = 1; _currentTotalCount = context.Count; context.Commit(); Project serverProject = TemplateContainer.Resove <Project>(PrjCmdId.Service); serverProject.SetLog4netWatch(); CommonContainer.CommonServer.SetStartup(serverProject); //保存解决方案 if (_dte.Solution.Saved == false) { _dte.Solution.SaveAs(_dte.Solution.FullName); KeywordContainer.SetContainer(); } } catch (Exception ex) { Utility.Help.MsgBoxHelp.ShowError("Entity2Code Error:", ex); } }
private static Column CreateColumn(IDataRecord rdr, Regex rxClean, Table table, bool useCamelCase, Regex columnFilterExclude, Func <Column, Table, Column> updateColumn) { try { if (rdr == null) { throw new ArgumentNullException("rdr"); } string typename = rdr["TYPENAME"].ToString().Trim().ToLower(); var scale = decimal.ToInt32(decimal.Parse(rdr["SCALE"].ToString())); var precision = decimal.ToInt32(decimal.Parse(rdr["PRECISION"].ToString())); if (typename.ToLower() == "number" && scale == 0 && precision == 0) { scale = int.MinValue; precision = 38; } var col = new Column { Name = rdr["COLUMNNAME"].ToString().Trim(), TypeName = typename, PropertyType = GetPropertyType(typename, ref scale, precision), MaxLength = decimal.ToInt32(decimal.Parse(rdr["MAXLENGTH"].ToString())), Precision = precision, Default = rdr["Default"].ToString().Trim(), DateTimePrecision = decimal.ToInt32(decimal.Parse(rdr["DATETIMEPRECISION"].ToString())), Scale = scale, Ordinal = decimal.ToInt32(decimal.Parse(rdr["ORDINAL"].ToString())), IsIdentity = rdr["ISIDENTITY"].ToString().Trim().ToLower() == "1", IsNullable = rdr["ISNULLABLE"].ToString().Trim().ToLower() == "1", IsStoreGenerated = rdr["ISSTOREGENERATED"].ToString().Trim().ToLower() == "1", IsPrimaryKey = rdr["PRIMARYKEY"].ToString().Trim().ToLower() == "1", PrimaryKeyOrdinal = decimal.ToInt32(decimal.Parse(rdr["PRIMARYKEYORDINAL"].ToString())), IsForeignKey = rdr["ISFOREIGNKEY"].ToString().Trim().ToLower() == "1" }; Assembly asm = Assembly.Load("EntityFramework"); Version v = new Version("5.0.0.0"); if (typename.ToLower() == "float" && asm.GetName().Version > v) { if (precision == 126) { col.Precision = 38; } else if (precision == 63) { col.Precision = 19; } } if (columnFilterExclude != null && !col.IsPrimaryKey && columnFilterExclude.IsMatch(col.Name)) { col.Hidden = true; } col.IsFixedLength = (typename.ToLower() == "char" || typename.ToLower() == "nchar"); col.IsUnicode = !(typename.ToLower() == "char" || typename.ToLower() == "varchar2" || typename.ToLower() == "clob" || typename.ToLower() == "long"); col.IsRowVersion = col.IsStoreGenerated && !col.IsNullable && typename == "timestamp"; if (col.IsRowVersion) { col.MaxLength = 8; } col.CleanUpDefault(); col.PropertyName = CodeFirstTools.CleanUp(col.Name); col.PropertyName = rxClean.Replace(col.PropertyName, "_$1"); // Make sure property name doesn't clash with class name if (col.PropertyName == table.NameHumanCase) { col.PropertyName = col.PropertyName + "_"; } col.PropertyNameHumanCase = (useCamelCase ? Inflector.ToTitleCase(col.PropertyName) : col.PropertyName).Replace(" ", ""); if (col.PropertyNameHumanCase == string.Empty) { col.PropertyNameHumanCase = col.PropertyName; } // Make sure property name doesn't clash with class name if (col.PropertyNameHumanCase == table.NameHumanCase) { col.PropertyNameHumanCase = col.PropertyNameHumanCase + "_"; } if (char.IsDigit(col.PropertyNameHumanCase[0])) { col.PropertyNameHumanCase = "_" + col.PropertyNameHumanCase; } if (CodeFirstTools.CheckNullable(col) != string.Empty) { table.HasNullableColumns = true; } col = updateColumn(col, table); // If PropertyType is empty, return null. Most likely ignoring a column due to legacy (such as OData not supporting spatial types) if (string.IsNullOrEmpty(col.PropertyType)) { return(null); } return(col); } catch (Exception ee) { throw ee; } }
private static Column CreateColumn(IDataRecord rdr, Regex rxClean, Table table, bool useCamelCase, Regex columnFilterExclude, Func <Column, Table, Column> updateColumn) { if (rdr == null) { throw new ArgumentNullException("rdr"); } string typename = rdr["TypeName"].ToString().Trim().ToLower(); var scale = (int)rdr["Scale"]; var precision = (int)rdr["Precision"]; var col = new Column { Name = rdr["ColumnName"].ToString().Trim(), TypeName = typename, PropertyType = GetPropertyType(typename, scale, precision), MaxLength = (int)rdr["MaxLength"], Precision = precision, Default = rdr["Default"].ToString().Trim(), DateTimePrecision = (int)rdr["DateTimePrecision"], Scale = scale, Ordinal = (int)rdr["Ordinal"], IsIdentity = rdr["IsIdentity"].ToString().Trim().ToLower() == "true", IsNullable = rdr["IsNullable"].ToString().Trim().ToLower() == "true", IsStoreGenerated = rdr["IsStoreGenerated"].ToString().Trim().ToLower() == "true", IsPrimaryKey = rdr["PrimaryKey"].ToString().Trim().ToLower() == "true", PrimaryKeyOrdinal = (int)rdr["PrimaryKeyOrdinal"], IsForeignKey = rdr["IsForeignKey"].ToString().Trim().ToLower() == "true" }; if (columnFilterExclude != null && !col.IsPrimaryKey && columnFilterExclude.IsMatch(col.Name)) { col.Hidden = true; } col.IsFixedLength = (typename == "char" || typename == "nchar"); col.IsUnicode = !(typename == "char" || typename == "varchar" || typename == "text"); col.IsRowVersion = col.IsStoreGenerated && !col.IsNullable && typename == "timestamp"; if (col.IsRowVersion) { col.MaxLength = 8; } col.CleanUpDefault(); col.PropertyName = CodeFirstTools.CleanUp(col.Name); col.PropertyName = rxClean.Replace(col.PropertyName, "_$1"); // Make sure property name doesn't clash with class name if (col.PropertyName == table.NameHumanCase) { col.PropertyName = col.PropertyName + "_"; } col.PropertyNameHumanCase = (useCamelCase ? Inflector.ToTitleCase(col.PropertyName) : col.PropertyName).Replace(" ", ""); if (col.PropertyNameHumanCase == string.Empty) { col.PropertyNameHumanCase = col.PropertyName; } // Make sure property name doesn't clash with class name if (col.PropertyNameHumanCase == table.NameHumanCase) { col.PropertyNameHumanCase = col.PropertyNameHumanCase + "_"; } if (char.IsDigit(col.PropertyNameHumanCase[0])) { col.PropertyNameHumanCase = "_" + col.PropertyNameHumanCase; } if (CodeFirstTools.CheckNullable(col) != string.Empty) { table.HasNullableColumns = true; } col = updateColumn(col, table); // If PropertyType is empty, return null. Most likely ignoring a column due to legacy (such as OData not supporting spatial types) if (string.IsNullOrEmpty(col.PropertyType)) { return(null); } return(col); }