void AddNamespaceMapping(EntityCodeGenerator entityCodeGenerator, XElement schema, string outputNamespace) { if (!String.IsNullOrEmpty(outputNamespace)) { AddNamespaceMapping(entityCodeGenerator, schema.Attribute(XName.Get("Namespace")), outputNamespace); } }
void AddNamespaceMapping(EntityCodeGenerator entityCodeGenerator, XAttribute edmNamespace, string outputNamespace) { if (edmNamespace != null) { entityCodeGenerator.EdmToObjectNamespaceMap.Add(edmNamespace.Value, outputNamespace); } }
private void btnGenerate_Click(object sender, EventArgs e) { var properties = ParsePropertiesFromHtml(tbProperties.Text, false).ToList(); var roProperties = ParsePropertiesFromHtml(tbROProperties.Text, true).ToList(); var unsetProperties = tbUnsetProperties.Text. Split('\n') .Select(line => line.Trim()) .Where(line => !string.IsNullOrEmpty(line)) .Select(line => line.Split(new string[] { "--" }, StringSplitOptions.RemoveEmptyEntries).Select(i => i.Trim()).First()) .ToArray(); //first column for each row foreach (var unsetProp in unsetProperties) { var p = properties.SingleOrDefault(prop => prop.FieldName == unsetProp); if (p != null) { p.UseUnset = true; } } tbSourceCode.Text = EntityCodeGenerator.Generate(tbEntityPath.Text, tbDescription.Text, false, new List <ParsedProperty> { new ParsedProperty("Id", ".id", "primary key of row", "string", true, true, null) } .Concat(properties) .Concat(roProperties)); tbSourceCode.SelectAll(); tbSourceCode.Focus(); }
public void GenerateCode(FileProjectItem item, CustomToolContext context) { LanguageOption languageToGenerateCode = LanguageOption.GenerateCSharpCode; if (item.Project.Language != "C#") { languageToGenerateCode = LanguageOption.GenerateVBCode; } XDocument edmxDocument = XDocument.Load(item.FileName); XElement conceptualModelsElement = EDMXIO.ReadSection(edmxDocument, EDMXIO.EDMXSection.CSDL); if (conceptualModelsElement == null) { throw new ArgumentException("Input file is not a valid EDMX file."); } XDocument csdlDocument = new XDocument(new XDeclaration("1.0", "utf-8", null), conceptualModelsElement.Element(XName.Get("Schema", csdlNamespace.NamespaceName))); string tempFileName = IO.GetTempFilenameWithExtension("csdl"); csdlDocument.Save(tempFileName); string outputFileName = context.GetOutputFileName(item, "Designer"); EntityCodeGenerator entityCodeGenerator = new EntityCodeGenerator(languageToGenerateCode); IList <EdmSchemaError> edmSchemaErrors = entityCodeGenerator.GenerateCode(tempFileName, outputFileName); File.Delete(tempFileName); context.EnsureOutputFileIsInProject(item, outputFileName); }
private void InitializeSettings() { Classes = new EntityClassGenerator(LanguageOption.GenerateCSharpCode); Code = new EntityCodeGenerator(LanguageOption.GenerateCSharpCode); Views = new EntityViewGenerator(LanguageOption.GenerateCSharpCode); Store = new EntityStoreSchemaGenerator(providerInvariantName, connectionString, "ShoppingModelStore"); Store.GenerateForeignKeyProperties = true; }
public override void GenerateCode(AssemblyBuilder assemblyBuilder) { // look at the assembly builder to see which language we should use in the App_Code directory EntityCodeGenerator generator = null; if (assemblyBuilder.CodeDomProvider.FileExtension.ToLowerInvariant() == "cs") { generator = new EntityCodeGenerator(LanguageOption.GenerateCSharpCode); } else { generator = new EntityCodeGenerator(LanguageOption.GenerateVBCode); } // generate the code for our CSDL file IList <EdmSchemaError> errors = null; using (XmlReader input = XmlReader.Create(VirtualPathProvider.OpenFile(base.VirtualPath))) { using (StringWriter output = new StringWriter(CultureInfo.InvariantCulture)) { // Read from input and generate into output, put errors in a class member var entityFrameworkVersion = GetEntityFrameworkVersion(BuildManager.TargetFramework.Version); errors = generator.GenerateCode(input, output, entityFrameworkVersion); if (errors.Count == 0) { output.Flush(); assemblyBuilder.AddCodeCompileUnit(this, new CodeSnippetCompileUnit(output.ToString())); } } } // if there are errors, package this data into XmlExceptions and throw this // if we are in VS, the ASP .NET stack will place this information in the error pane // if we are in the ASP .NET runtime, it will use this information to build the error page if (errors != null && errors.Count > 0) { XmlException inner = null; XmlException outer = null; foreach (EdmSchemaError error in errors) { outer = new XmlException(error.Message, inner, error.Line, error.Column); inner = outer; } throw outer; } BuildProviderUtils.AddArtifactReference(assemblyBuilder, this, base.VirtualPath); }
public void GenerateCode(FileProjectItem item, CustomToolContext context) { XElement schema = GetModelSchema(item); XDocument csdlDocument = CreateCsdlDocument(schema); string tempFileName = IO.GetTempFilenameWithExtension("csdl"); csdlDocument.Save(tempFileName); LanguageOption languageToGenerateCode = GetLanguageOption(item); string outputFileName = context.GetOutputFileName(item, "Designer"); EntityCodeGenerator entityCodeGenerator = new EntityCodeGenerator(languageToGenerateCode); AddNamespaceMapping(entityCodeGenerator, schema, context.OutputNamespace); IList <EdmSchemaError> edmSchemaErrors = entityCodeGenerator.GenerateCode(tempFileName, outputFileName); File.Delete(tempFileName); context.EnsureOutputFileIsInProject(item, outputFileName); }
private void GenerateCode() { CSDLTemplate csdl = new CSDLTemplate(_model); XDocument document = XDocument.Parse(csdl.FileContent); XElement c = EdmGen2.GetCsdlFromEdmx(document, EntityFrameworkVersions.Version2); // generate code StringWriter sw = new StringWriter(); EntityCodeGenerator codeGen = new EntityCodeGenerator(LanguageOption.GenerateCSharpCode); IList <EdmSchemaError> errors = codeGen.GenerateCode(c.CreateReader(), sw); if (errors.Count != 0) { //throw new Exception("The Entity Framework generation failed. Please email [email protected]."); StringBuilder sb = new StringBuilder(); foreach (EdmSchemaError error in errors) { sb.AppendFormat("error.Column:{0} error.ErrorCode:{1} error.Line:{2} error.Message:{3} error.SchemaLocation:{4} error.SchemaName:{5} error.Severity:{6} error.StackTrace: {7}", error.Column, error.ErrorCode, error.Line, error.Message, error.SchemaLocation, error.SchemaName, error.Severity, error.StackTrace).AppendLine(); } System.Diagnostics.Debug.WriteLine(sb.ToString()); } }
private static void CodeGen(FileInfo edmxFile, LanguageOption languageOption) { XDocument xdoc = XDocument.Load(edmxFile.FullName); XElement c = GetCsdlFromEdmx(xdoc); Version v = _namespaceManager.GetVersionFromEDMXDocument(xdoc); StringWriter sw = new StringWriter(); IList <EdmSchemaError> errors = null; // // code-gen uses different classes for V1 and V2 of the EF // if (v == EntityFrameworkVersions.Version1) { // generate code EntityClassGenerator codeGen = new EntityClassGenerator(languageOption); errors = codeGen.GenerateCode(c.CreateReader(), sw); } else if (v == EntityFrameworkVersions.Version2) { EntityCodeGenerator codeGen = new EntityCodeGenerator(languageOption); errors = codeGen.GenerateCode(c.CreateReader(), sw); } else if (v == EntityFrameworkVersions.Version3) { EntityCodeGenerator codeGen = new EntityCodeGenerator(languageOption); errors = codeGen.GenerateCode(c.CreateReader(), sw, EntityFrameworkVersions.Version3); } // write out code-file string outputFileName = GetFileNameWithNewExtension(edmxFile, GetFileExtensionForLanguageOption(languageOption)); File.WriteAllText(outputFileName, sw.ToString()); // output errors WriteErrors(errors); }
/// <summary> /// 生成代码. /// </summary> /// <param name="codeNamespace">生成代码的命名空间.</param> /// <param name="tables">仅为这些表生成代码.</param> public void BuildTo(string codeNamespace, List <TableInfoModel> tables = null) { List <TableInfoModel> buildTables; if (tables != null && tables.Count > 0) { buildTables = tables; } else { buildTables = AllTables.Distinct(p => p.tableName).ToList(); } if (buildTables == null || buildTables.Count < 1) { return; } // 创建代码生成器. CodeGenerator entityGenerator = null, agentGenerator = null, contGenerator = null; switch (Pattern) { case BuildPattern.BuildEntity: entityGenerator = new EntityCodeGenerator(); entityGenerator.LangComments = Language; break; case BuildPattern.BuildAgent: agentGenerator = new EntityAgentCodeGenerator(); agentGenerator.LangComments = Language; contGenerator = new EntityContextGenerator(); contGenerator.LangComments = Language; break; default: entityGenerator = new EntityCodeGenerator(); entityGenerator.LangComments = Language; agentGenerator = new EntityAgentCodeGenerator(); agentGenerator.LangComments = Language; contGenerator = new EntityContextGenerator(); contGenerator.LangComments = Language; break; } // 开始生成代码. CodeClassDeclaration entityClass, contextClass, agentClass; List <TableInfoModel> currentTable; for (int i = 0; i < buildTables.Count; ++i) { int bfb = (int)(Convert.ToSingle(i) / buildTables.Count * 100); currentTable = AllTables.Where(item => item.tableName == buildTables[i].tableName).ToList(); if (entityGenerator != null) // 生成实体类的代码. { OnProgressChange(bfb, string.Format(Language.GetString("BuildingEntityClass"), buildTables[i].tableName)); entityClass = new CodeClassDeclaration(currentTable); entityClass.BaseTypes.Add("DataEntity"); entityClass.CodeComment = buildTables[i].tableDescription; entityClass.Namespace = codeNamespace; entityClass.Name = buildTables[i].tableName; entityClass.TableName = buildTables[i].tableName; entityGenerator.AddClass(entityClass); entityGenerator.WriteTo(Path.Combine(OutputDir, string.Format("{0}.cs", buildTables[i].tableName)), true); } if (agentGenerator != null) { OnProgressChange(bfb, string.Format(Language.GetString("BuildingAgentClass"), buildTables[i].tableName)); agentClass = new CodeClassDeclaration(currentTable); agentClass.BaseTypes.Add("EntityAgent"); agentClass.CodeComment = string.Format(Language.GetString("AgentClassComment"), buildTables[i].tableDescription); agentClass.Namespace = codeNamespace; agentClass.Name = string.Format("{0}Agent", buildTables[i].tableName); agentClass.TableName = buildTables[i].tableName; agentGenerator.AddClass(agentClass); OnProgressChange(bfb, string.Format(Language.GetString("BuildingContextClass"), buildTables[i].tableName)); contextClass = new CodeClassDeclaration(currentTable); contextClass.BaseTypes.Add(string.Format("TableContext<{0}Agent>", buildTables[i].tableName)); contextClass.CodeComment = string.Format(Language.GetString("ContextClassComment"), buildTables[i].tableName); contextClass.Namespace = codeNamespace; contextClass.Name = string.Format("{0}Context", buildTables[i].tableName); contextClass.TableName = buildTables[i].tableName; agentGenerator.AddClass(contGenerator.BuildClass(contextClass)); agentGenerator.WriteTo(Path.Combine(OutputDir, string.Format("{0}Context.cs", buildTables[i].tableName)), true); } } }
public void cc() { String connectionString = "Data Source=.;Initial Catalog=MyDB;User Id=sa;Password=sa;"; String dataBaseType = "SQLServer"; Draco.DB.QuickDataBase.Configuration.ConnectionInfo connInfo = new ConnectionInfo(connectionString, dataBaseType); Draco.DB.QuickDataBase.IDataBaseContext ctx = new Draco.DB.QuickDataBase.DataBaseContext(connInfo); Draco.DB.QuickDataBase.IDataBaseHandler handler = ctx.Handler; //开始数据库操作 //...... //以IDataBaseHandler对象获取Draco.DB.QuickDataBase.IDataBaseContext对象 Draco.DB.QuickDataBase.Adapter.IDataBaseAdapter adp = handler.DbAdapter; //创建单一参数对象 System.Data.IDataParameter para = adp.CreateParameter("@Para", "abc"); //快速创建参数化对象数组 Draco.DB.QuickDataBase.IDataParameters parameters = new Draco.DB.QuickDataBase.Common.DataParameters(adp); parameters.AddParameterValue("FiledNameX", 1); parameters.AddParameterValue("FiledNameY", "abc"); parameters.AddParameterValue("FiledNameZ", DateTime.Now); System.Data.IDataParameter[] _Parameters = parameters.Parameters; String SQL = "select * from tab where field1=? and (field2=? or field3>?)"; Draco.DB.QuickDataBase.ParameterizedSQL param = handler.DbAdapter.AdaptSQLAnonymousParams(SQL, 100, "ABC", DateTime.Now); DataSet ds = handler.ExecuteQuery(param.SQL, param.Parameters); Draco.DB.QuickDataBase.ISQLGenerator SQLGen = adp.GetSQLGenerator(); Draco.DB.QuickDataBase.IDataBaseSchemaHandler schemaHandler = adp.GetSchemaHandler(handler); String timeSQL = adp.NamedSQLs["Test.TimeSQL"]; Object obj = handler.ExecuteScalar(timeSQL); // ctx.Handler.StartTransaction(); ctx.Handler.CommitTransaction(); handler.StartTransaction(); handler.CommitTransaction(); using (Draco.DB.QuickDataBase.Common.DbTransactionScope scope = new DbTransactionScope(handler)) { try { //.... scope.Complete();// } catch { } } Draco.DB.ORM.IORMContext octx = new ORMContext(connInfo); Draco.DB.ORM.Schema.Vendor.ISchemaLoader Loader = octx.SchemaLoader; //获取加载器 Draco.DB.ORM.Schema.Dbml.Database dataBase = Loader.Load("Name", "Draco.DataTblCtrlLayer", null); //加载数据库构架 Draco.DB.ORM.Generator.EntityCodeGenerator Generator = new EntityCodeGenerator(dataBase); //创建代码生成器 string Code = Generator.GenerateCode("MyEntity", "GUID", true); //创建C#代码 System.IO.File.WriteAllText("D:\\MyEntity.cs", Code, System.Text.Encoding.UTF8); //输出C#代码到文件 }