Exemplo n.º 1
0
        /// <summary>
        /// 生成一般的model类
        /// </summary>
        /// <param name="db"></param>
        /// <param name="nameSpace"></param>
        /// <param name="table"></param>
        /// <returns></returns>
        public void BuildSimpleTable(EJDB db, NamespaceCode namespaceCode, EJ.DBTable table)
        {
            var columns = db.DBColumn.Where(m => m.TableID == table.id).ToList();

            BuildSimpleTable(db, namespaceCode, table, columns);
        }
Exemplo n.º 2
0
        static void BuildSimpleTable(EJDB db, NamespaceCode namespaceCode, EJ.DBTable table, List <EJ.DBColumn> columns)
        {
            var pkcolumn = columns.FirstOrDefault(m => m.IsPKID == true);


            CodeItem classCode = new CodeItem($"public class {table.Name} :Way.Lib.DataModel");

            namespaceCode.AddItem(classCode);
            classCode.Comment = table.caption;

            //构造函数
            classCode.AddItem(new CodeItem($"public {table.Name}()").AddString(""));

            foreach (var column in columns)
            {
                FieldCodeItem fieldCodeItem = new FieldCodeItem($"_{column.Name}");
                classCode.AddItem(fieldCodeItem);
                PropertyCodeItem proCodeItem = new PropertyCodeItem(column.Name);
                classCode.AddItem(proCodeItem);
                proCodeItem.Comment = column.caption;


                string dataType = GetLinqTypeString(column.dbType, column.CanNull.GetValueOrDefault() || column.IsAutoIncrement == true);

                string eqString = "";
                if (!string.IsNullOrEmpty(column.EnumDefine) && column.dbType == "int")
                {
                    if (column.EnumDefine.Trim().StartsWith("$"))
                    {
                        var target = column.EnumDefine.Trim().Substring(1).Split('.');
                        if (column.CanNull == true)
                        {
                            dataType = target[0] + "_" + target[1] + "Enum?";
                        }
                        else
                        {
                            dataType = target[0] + "_" + target[1] + "Enum";
                        }
                    }
                    else
                    {
                        string[] enumitems = column.EnumDefine.Replace("\r", "").Split('\n');

                        CodeItem codeEnum = new CodeItem($"public enum {table.Name}_{column.Name}Enum:int");
                        namespaceCode.AddItem(codeEnum);

                        CodeItem codeEnumField = new CodeItem();
                        for (int i = 0; i < enumitems.Length; i++)
                        {
                            var code = enumitems[i].Trim();
                            if (code.Length == 0)
                            {
                                continue;
                            }
                            if (code.StartsWith("//"))
                            {
                                if (code.Length > 2)
                                {
                                    if (codeEnumField.Comment.Length > 0)
                                    {
                                        codeEnumField.Comment += "\r\n";
                                    }
                                    codeEnumField.Comment += code.Substring(2);
                                }
                            }
                            else
                            {
                                codeEnumField.Body = code;
                                codeEnum.AddItem(codeEnumField);
                                codeEnumField = new CodeItem();
                            }
                        }
                        if (column.CanNull == true)
                        {
                            dataType = table.Name + "_" + column.Name + "Enum?";
                        }
                        else
                        {
                            dataType = table.Name + "_" + column.Name + "Enum";
                        }
                    }
                }


                if (!string.IsNullOrEmpty(column.defaultValue))
                {
                    if (column.defaultValue.Trim().Length > 0)
                    {
                        eqString = column.defaultValue.Trim();
                        if (dataType == "String")
                        {
                            if (eqString.StartsWith("'") && eqString.EndsWith("'") && eqString.Length > 1)
                            {
                                eqString = eqString.Substring(1, eqString.Length - 2);
                            }
                            eqString = "\"" + eqString + "\"";
                        }
                        else if (dataType == "System.Nullable<Decimal>" || dataType == "Decimal")
                        {
                            eqString = eqString + "m";
                        }
                        else if (dataType == "System.Nullable<float>" || dataType == "float")
                        {
                            eqString = eqString + "f";
                        }
                        else if (dataType == "System.Nullable<Boolean>" || dataType == "Boolean")
                        {
                            if (eqString == "1")
                            {
                                eqString = "true";
                            }
                            else if (eqString == "0")
                            {
                                eqString = "false";
                            }
                        }
                        else if (!string.IsNullOrEmpty(column.EnumDefine) && column.dbType == "int")
                        {
                            eqString = "(" + dataType + ")(" + eqString + ")";
                        }
                        eqString = "=" + eqString;
                    }
                }

                fieldCodeItem.FieldType  = dataType;
                proCodeItem.PropertyType = dataType;
                proCodeItem.Modification = "public virtual";
                proCodeItem.ItemForGet.AddString($"return _{column.Name};");
                proCodeItem.ItemForSet.AddItem(new CodeItem($"if ((_{column.Name} != value))")
                                               .AddString($"var original = _{column.Name};")
                                               .AddString($"_{column.Name} = value;")
                                               .AddString($"OnPropertyChanged(\"{column.Name.Trim()}\",original,value);")
                                               );
            }


            var classProperties = db.classproperty.Where(m => m.tableid == table.id).ToArray();

            foreach (var pro in classProperties)
            {
                try
                {
                    var foreign_table = db.DBTable.FirstOrDefault(m => m.id == pro.foreignkey_tableid);
                    if (pro.iscollection == false)
                    {
                        var column = db.DBColumn.FirstOrDefault(m => m.id == pro.foreignkey_columnid);
                        classCode.AddItem(new PropertyCodeItem(pro.name)
                        {
                            PropertyType = foreign_table.Name,
                            Modification = "public virtual"
                        });
                    }
                    else
                    {
                        //与其他表多对一
                        classCode.AddItem(new PropertyCodeItem(pro.name)
                        {
                            PropertyType = $"ICollection<{foreign_table.Name}>",
                            Modification = "public virtual"
                        });
                    }
                }
                catch
                {
                }
            }
        }
Exemplo n.º 3
0
        static void BuildTable(EJDB db, NamespaceCode namespaceCode, EJ.DBTable table, List <EJ.DBColumn> columns, List <string> foreignKeys)
        {
            var      pkcolumn  = columns.FirstOrDefault(m => m.IsPKID == true);
            CodeItem classCode = new CodeItem($"public class {table.Name} :Way.EntityDB.DataItem");

            namespaceCode.AddItem(classCode);
            classCode.Comment = table.caption;

            Dictionary <string, CodeItem> otherClassCode = new Dictionary <string, CodeItem>();
            var discriminatorColumn = columns.FirstOrDefault(m => m.IsDiscriminator == true && !string.IsNullOrEmpty(m.EnumDefine?.Trim()));

            ClassName[] classNames = null;
            if (discriminatorColumn != null)
            {
                classNames = ParseNames(discriminatorColumn.EnumDefine).ToArray();
                classCode.Attributes.Add(@"[TableConfig( AutoSetPropertyNameOnInsert = """ + discriminatorColumn.Name + @""" , AutoSetPropertyValueOnInsert=(" + table.Name + "_" + discriminatorColumn.Name + @"Enum)0)]");

                foreach (var classnameitem in classNames)
                {
                    var myClsCodeItem = new CodeItem($"public class {classnameitem.Name} :{((classnameitem.BaseName == null) ? table.Name : classnameitem.BaseName)}");
                    namespaceCode.AddItem(myClsCodeItem);
                    myClsCodeItem.Comment = classnameitem.Comment;
                    myClsCodeItem.Attributes.Add(@"[TableConfig(AutoSetPropertyNameOnInsert = """ + discriminatorColumn.Name + @""" , AutoSetPropertyValueOnInsert=" + table.Name + "_" + discriminatorColumn.Name + @"Enum." + classnameitem.Name + @")]");
                    otherClassCode[classnameitem.Name] = myClsCodeItem;
                    myClsCodeItem.AddString("");
                }
            }
            else
            {
                classCode.Attributes.Add("[TableConfig]");
            }

            classCode.Attributes.Add($"[Table(\"{table.Name.ToLower()}\")]");
            classCode.Attributes.Add("[Way.EntityDB.DataItemJsonConverter]");


            CodeItem curClassCodeItem = null;

            foreach (var column in columns)
            {
                if (discriminatorColumn != null && classNames != null && !string.IsNullOrEmpty(column.ClassName?.Trim()) && columns.Any(m => m.IsDiscriminator == true) &&
                    otherClassCode.ContainsKey(column.ClassName))
                {
                    curClassCodeItem = otherClassCode[column.ClassName];
                }
                else
                {
                    curClassCodeItem = classCode;
                }

                PropertyCodeItem columnCodeItem = new PropertyCodeItem(column.Name);
                columnCodeItem.Modification = "public virtual";

                string caption = column.caption == null ? "" : column.caption;
                if (caption.Contains(","))
                {
                    caption = caption.Substring(0, caption.IndexOf(","));
                }
                else if (caption.Contains(","))
                {
                    caption = caption.Substring(0, caption.IndexOf(","));
                }

                string dataType = GetLinqTypeString(column.dbType, column.CanNull.GetValueOrDefault() || column.IsAutoIncrement == true);


                string eqString = "";
                if (!string.IsNullOrEmpty(column.EnumDefine) && column.dbType == "int")
                {
                    if (column.EnumDefine.Trim().StartsWith("$"))
                    {
                        var target = column.EnumDefine.Trim().Substring(1).Split('.');
                        if (column.CanNull == true)
                        {
                            dataType = target[0] + "_" + target[1] + "Enum?";
                        }
                        else
                        {
                            dataType = target[0] + "_" + target[1] + "Enum";
                        }
                    }
                    else
                    {
                        string[] enumitems = column.EnumDefine.Replace("\r", "").Split('\n');

                        CodeItem codeEnum = new CodeItem($"public enum {table.Name}_{column.Name}Enum:int");
                        namespaceCode.AddItem(codeEnum);

                        CodeItem codeEnumField = new CodeItem();
                        for (int i = 0; i < enumitems.Length; i++)
                        {
                            var code = enumitems[i].Trim();
                            if (code.Length == 0)
                            {
                                continue;
                            }
                            if (code.StartsWith("//"))
                            {
                                if (code.Length > 2)
                                {
                                    if (codeEnumField.Comment.Length > 0)
                                    {
                                        codeEnumField.Comment += "\r\n";
                                    }
                                    codeEnumField.Comment += code.Substring(2);
                                }
                            }
                            else
                            {
                                codeEnumField.Body = code;
                                codeEnum.AddItem(codeEnumField);
                                codeEnumField = new CodeItem();
                            }
                        }
                        if (column.CanNull == true)
                        {
                            dataType = table.Name + "_" + column.Name + "Enum?";
                        }
                        else
                        {
                            dataType = table.Name + "_" + column.Name + "Enum";
                        }
                    }
                }


                if (!string.IsNullOrEmpty(column.defaultValue))
                {
                    if (column.defaultValue.Trim().Length > 0)
                    {
                        eqString = column.defaultValue.Trim();
                        if (dataType == "String")
                        {
                            if (eqString.StartsWith("'") && eqString.EndsWith("'") && eqString.Length > 1)
                            {
                                eqString = eqString.Substring(1, eqString.Length - 2);
                            }
                            eqString = "\"" + eqString + "\"";
                        }
                        else if (dataType == "System.Nullable<Decimal>" || dataType == "Decimal")
                        {
                            eqString = eqString + "m";
                        }
                        else if (dataType == "System.Nullable<float>" || dataType == "float")
                        {
                            eqString = eqString + "f";
                        }
                        else if (dataType == "System.Nullable<Boolean>" || dataType == "Boolean")
                        {
                            if (eqString == "1")
                            {
                                eqString = "true";
                            }
                            else if (eqString == "0")
                            {
                                eqString = "false";
                            }
                        }
                        else if (!string.IsNullOrEmpty(column.EnumDefine) && column.dbType == "int")
                        {
                            eqString = "(" + dataType + ")(" + eqString + ")";
                        }
                        eqString = "=" + eqString;
                    }
                }

                if (column.dbType.Contains("char"))
                {
                    try
                    {
                        columnCodeItem.Attributes.Add($"[MaxLength({Convert.ToInt32(column.length)})]");
                    }
                    catch
                    {
                    }
                }

                if (column.IsPKID == true)
                {
                    columnCodeItem.Attributes.Add("[Key]");
                }
                if (column.IsAutoIncrement == true)
                {
                    columnCodeItem.Attributes.Add("[DatabaseGenerated(DatabaseGeneratedOption.Identity)]");
                }
                if (column.CanNull == false)
                {
                    columnCodeItem.Attributes.Add("[DisallowNull]");
                    //columnCodeItem.Attributes.Add("[Required]");
                }
                if (!string.IsNullOrEmpty(column.caption))
                {
                    columnCodeItem.Attributes.Add($"[Display(Name = \"{column.caption.Replace("\r","").Replace("\n"," ").Replace("\"", "\\\"")}\")]");
                }

                columnCodeItem.Attributes.Add($"[Column(\"{column.Name.ToLower()}\")]");
                columnCodeItem.PropertyType = dataType;
                columnCodeItem.Comment      = column.caption;
                curClassCodeItem.AddString($"{dataType} _{column.Name + eqString};");
                curClassCodeItem.AddItem(columnCodeItem);

                columnCodeItem.ItemForGet.AddString($"return _{column.Name};");
                columnCodeItem.ItemForSet.AddString($"if ((_{column.Name} != value))");
                columnCodeItem.ItemForSet.AddString("{");
                columnCodeItem.ItemForSet.AddString($"    SendPropertyChanging(\"{column.Name.Trim()}\",_{column.Name.Trim()},value);");
                columnCodeItem.ItemForSet.AddString($"    _{column.Name} = value;");
                columnCodeItem.ItemForSet.AddString($"    SendPropertyChanged(\"{column.Name.Trim()}\");");
                columnCodeItem.ItemForSet.AddString("}");
            }

            var classProperties = db.classproperty.Where(m => m.tableid == table.id).ToArray();

            foreach (var pro in classProperties)
            {
                try {
                    var foreign_table = db.DBTable.FirstOrDefault(m => m.id == pro.foreignkey_tableid);
                    var column        = db.DBColumn.FirstOrDefault(m => m.id == pro.foreignkey_columnid);


                    if (pro.iscollection == false)
                    {
                        if (column != null && column.TableID == table.id)
                        {
                            var procodeitem = new CodeItem($"public virtual {foreign_table.Name} {pro.name} {{ get; set; }}");
                            classCode.AddItem(procodeitem);

                            if (foreignKeys.Contains($"{table.Name}->{column.Name}") == false)
                            {
                                foreignKeys.Add($"{table.Name}->{column.Name}");
                                procodeitem.Attributes.Add(@"[ForeignKey(""" + column.Name + @""")]");
                            }
                        }
                        else
                        {
                            //与其他表一对一
                            var procodeitem = new CodeItem($"public virtual {foreign_table.Name} {pro.name} {{ get; set; }}");
                            classCode.AddItem(procodeitem);
                        }
                    }
                    else
                    {
                        if (column != null)
                        {
                            //与其他表多对一
                            var procodeitem = new CodeItem($"public virtual ICollection<{foreign_table.Name}> {pro.name} {{ get; set; }}");
                            classCode.AddItem(procodeitem);

                            if (foreignKeys.Contains($"{foreign_table.Name}->{column.Name}") == false)
                            {
                                foreignKeys.Add($"{foreign_table.Name}->{column.Name}");
                                procodeitem.Attributes.Add(@"[ForeignKey(""" + column.Name + @""")]");
                            }
                        }
                    }
                }
                catch
                {
                }
            }
        }
Exemplo n.º 4
0
        public void BuildTable(EJDB db, NamespaceCode namespaceCode, EJ.DBTable table, List <string> foreignKeys)
        {
            var columns = db.DBColumn.Where(m => m.TableID == table.id).ToList();

            BuildTable(db, namespaceCode, table, columns, foreignKeys);
        }
Exemplo n.º 5
0
        public void BuilderDB(EJDB db, EJ.Databases databaseObj, NamespaceCode namespaceCode, List <EJ.DBTable> tables)
        {
            CodeItem classCode = new CodeItem($"public class {databaseObj.Name} : Way.EntityDB.DBContext");

            namespaceCode.AddItem(classCode);



            StringBuilder result = new StringBuilder();

            //构造函数
            CodeItem initFunc = new CodeItem($" public {databaseObj.Name}(string connection, Way.EntityDB.DatabaseType dbType , bool upgradeDatabase = true): base(connection, dbType , upgradeDatabase)");

            classCode.AddItem(initFunc);
            initFunc.AddString("if (!setEvented)");
            initFunc.AddString("{");
            initFunc.AddString("    lock (lockObj)");
            initFunc.AddString("    {");
            initFunc.AddString("        if (!setEvented)");
            initFunc.AddString("        {");
            initFunc.AddString("            setEvented = true;");
            initFunc.AddString("            Way.EntityDB.DBContext.BeforeDelete += Database_BeforeDelete;");
            initFunc.AddString("        }");
            initFunc.AddString("    }");
            initFunc.AddString("}");


            classCode.AddString("static object lockObj = new object();");
            classCode.AddString("static bool setEvented = false;");

            //级联删除
            CodeItem beforeDeleteFunc = new CodeItem("static void Database_BeforeDelete(object sender, Way.EntityDB.DatabaseModifyEventArg e)");

            classCode.AddItem(beforeDeleteFunc);
            beforeDeleteFunc.AddString($" var db =  sender as " + namespaceCode.NameSpace + "." + databaseObj.Name + @";");
            beforeDeleteFunc.AddString($"if (db == null) return;");

            StringBuilder _Database_deleteCodes = new StringBuilder();

            foreach (var t in tables)
            {
                var delConfigs = db.DBDeleteConfig.Where(m => m.TableID == t.id).ToList();

                if (delConfigs.Count > 0)
                {
                    CodeItem codeitem = new CodeItem($"if (e.DataItem is {t.Name})");
                    beforeDeleteFunc.AddItem(codeitem);
                    codeitem.AddString($"var deletingItem = ({t.Name})e.DataItem;");

                    StringBuilder codestrs = new StringBuilder();
                    for (int i = 0; i < delConfigs.Count; i++)
                    {
                        var configitem    = delConfigs[i];
                        var delDBTable    = db.DBTable.FirstOrDefault(m => m.id == configitem.RelaTableID);
                        var relaColumn    = db.DBColumn.FirstOrDefault(m => m.id == configitem.RelaColumID);
                        var rela_pkcolumn = db.DBColumn.FirstOrDefault(m => m.TableID == configitem.RelaTableID && m.IsPKID == true);
                        if (rela_pkcolumn == null)
                        {
                            throw new Exception("关联表" + delDBTable.Name + "没有定义主键");
                        }

                        codeitem.AddString($"var items{i} = (from m in db.{delDBTable.Name} where m.{relaColumn.Name} == deletingItem.id");
                        codeitem.AddItem(new CodeItem($"select new {delDBTable.Name}")
                                         .AddString($"{rela_pkcolumn.Name} = m.{rela_pkcolumn.Name}")
                                         );
                        codeitem.AddString(");");

                        codeitem.AddItem(new CodeItem("while(true)")
                                         .AddString($"var data2del = items{i}.Take(100).ToList();")
                                         .AddString("if(data2del.Count() ==0)")
                                         .AddString("    break;")
                                         .AddString("foreach (var t in data2del)")
                                         .AddString("{")
                                         .AddString("    t.ChangedProperties.Clear();")
                                         .AddString("    db.Delete(t);")
                                         .AddString("}")
                                         );
                    }
                    beforeDeleteFunc.AddString("");
                }
            }


            CodeItem modelbuildFunc = new CodeItem("protected override void OnModelCreating(ModelBuilder modelBuilder)");

            classCode.AddItem(modelbuildFunc);

            foreach (var t in tables)
            {
                var pkcolumn = db.DBColumn.FirstOrDefault(m => m.TableID == t.id && m.IsPKID == true);
                if (pkcolumn == null)
                {
                    throw new Exception(string.Format("表{0}缺少主键", t.Name));
                }
                modelbuildFunc.AddString($"modelBuilder.Entity<{t.Name}>().HasKey(m => m.{pkcolumn.Name});");

                var discriminatorColumn = db.DBColumn.FirstOrDefault(m => m.TableID == t.id && m.IsDiscriminator == true);
                if (discriminatorColumn != null)
                {
                    var classNames = ParseNames(discriminatorColumn.EnumDefine).ToArray();
                    if (discriminatorColumn.CanNull == true)
                    {
                        modelbuildFunc.AddString($"modelBuilder.Entity<{t.Name}>().HasDiscriminator<{t.Name}_{discriminatorColumn.Name}Enum?>(\"{discriminatorColumn.Name}\")");
                    }
                    else
                    {
                        modelbuildFunc.AddString($"modelBuilder.Entity<{t.Name}>().HasDiscriminator<{t.Name}_{discriminatorColumn.Name}Enum>(\"{discriminatorColumn.Name}\")");
                    }
                    modelbuildFunc.AddString($".HasValue<{t.Name}>(({t.Name}_{discriminatorColumn.Name}Enum)0)");

                    foreach (var classnameitem in classNames)
                    {
                        modelbuildFunc.AddString($".HasValue<{classnameitem.Name}>({t.Name}_{discriminatorColumn.Name}Enum.{classnameitem.Name})");
                    }
                    modelbuildFunc.AddString(";");
                }
            }


            foreach (var t in tables)
            {
                classCode.AddString($"System.Linq.IQueryable<{t.Name}> _{t.Name};");
                PropertyCodeItem proCodeItem = new PropertyCodeItem(t.Name);
                classCode.AddItem(proCodeItem);
                proCodeItem.Modification = "public virtual";
                proCodeItem.PropertyType = $"System.Linq.IQueryable<{t.Name}>";
                proCodeItem.ItemForSet   = null;
                proCodeItem.ItemForGet.AddString($"if (_{t.Name} == null)");
                proCodeItem.ItemForGet.AddString("{");
                proCodeItem.ItemForGet.AddString($"    _{t.Name} = this.Set<{t.Name}>();");
                proCodeItem.ItemForGet.AddString("}");
                proCodeItem.ItemForGet.AddString($"return _{t.Name};");

                var discriminatorColumn = db.DBColumn.FirstOrDefault(m => m.TableID == t.id && m.IsDiscriminator == true);
                if (discriminatorColumn != null)
                {
                    var classNames = ParseNames(discriminatorColumn.EnumDefine).ToArray();
                    foreach (var g in classNames)
                    {
                        classCode.AddString($"System.Linq.IQueryable<{g.Name}> _{g.Name};");
                        proCodeItem = new PropertyCodeItem(g.Name);
                        classCode.AddItem(proCodeItem);
                        proCodeItem.Modification = "public virtual";
                        proCodeItem.PropertyType = $"System.Linq.IQueryable<{g.Name}>";
                        proCodeItem.ItemForSet   = null;
                        proCodeItem.ItemForGet.AddString($"if (_{g.Name} == null)");
                        proCodeItem.ItemForGet.AddString("{");
                        proCodeItem.ItemForGet.AddString($"    _{g.Name} = this.Set<{g.Name}>();");
                        proCodeItem.ItemForGet.AddString("}");
                        proCodeItem.ItemForGet.AddString($"return _{g.Name};");
                    }
                }
            }
            result.Append("\r\n");



            string content = GetDesignData(db, databaseObj);

            var getDesignStringFunc = new CodeItem("protected override string GetDesignString()");

            classCode.AddItem(getDesignStringFunc);
            getDesignStringFunc.AddString("var result = new StringBuilder();");
            getDesignStringFunc.AddString($"result.Append(\"\\r\\n\");");

            for (int i = 0; i < content.Length; i += 200)
            {
                int len = Math.Min(content.Length - i, 200);
                getDesignStringFunc.AddString("result.Append(\"" + content.Substring(i, len) + "\");");
            }
            getDesignStringFunc.AddString("return result.ToString();");


            //记录数据库设计数据
            StringBuilder codeend = new StringBuilder();

            codeend.AppendLine("/*<design>");
            outputDesigns(codeend, db, databaseObj);
            codeend.AppendLine("<design>*/");

            namespaceCode.CodeEnd = codeend.ToString();
        }
Exemplo n.º 6
0
        public void Handle(string originalUrl, HttpConnectInformation connectInfo, ref bool handled)
        {
            if (originalUrl.Contains("/DownloadDatabaseCode.aspx") == false)
            {
                return;
            }
            handled = true;
            try
            {
                if (connectInfo.Session["user"] == null)
                {
                    throw new Exception("not arrow");
                }

                int databaseid = Convert.ToInt32(connectInfo.Request.Query["databaseid"]);
                using (EJDB db = new EJDB())
                {
                    var database = db.Databases.FirstOrDefault(m => m.id == databaseid);
                    if (database.dllPath == null || database.dllPath.StartsWith("{") == false)
                    {
                        database.dllPath = Newtonsoft.Json.JsonConvert.SerializeObject(new
                        {
                            db     = connectInfo.Request.Query["filepath"],
                            simple = "",
                        });
                    }
                    else
                    {
                        var json = (Newtonsoft.Json.Linq.JToken)Newtonsoft.Json.JsonConvert.DeserializeObject(database.dllPath);
                        json["db"]       = connectInfo.Request.Query["filepath"];
                        database.dllPath = json.ToString();
                    }
                    db.Update(database);

                    var tables = db.DBTable.Where(m => m.DatabaseID == databaseid).ToList();
                    System.IO.BinaryWriter bw = new System.IO.BinaryWriter(connectInfo.Response);
                    bw.Write("start");

                    var invokingDB = Way.EntityDB.Design.DBHelper.CreateInvokeDatabase(database);
                    IDatabaseDesignService dbservice = Way.EntityDB.Design.DBHelper.CreateDatabaseDesignService((Way.EntityDB.DatabaseType)(int) database.dbType);


                    bw.Write(1);
                    ICodeBuilder codeBuilder = new CodeBuilder();

                    NamespaceCode namespaceCode  = new NamespaceCode(database.NameSpace);
                    NamespaceCode namespaceCode2 = new NamespaceCode(database.NameSpace + ".DB");
                    namespaceCode.AddUsing("System");
                    namespaceCode.AddUsing("Microsoft.EntityFrameworkCore");
                    namespaceCode.AddUsing("System.Collections.Generic");
                    namespaceCode.AddUsing("System.ComponentModel");
                    namespaceCode.AddUsing("System.Data");
                    namespaceCode.AddUsing("System.Linq");
                    namespaceCode.AddUsing("System.Text");
                    namespaceCode.AddUsing("System.ComponentModel.DataAnnotations");
                    namespaceCode.AddUsing("System.ComponentModel.DataAnnotations.Schema");
                    namespaceCode.AddUsing("Way.EntityDB.Attributes");
                    namespaceCode.AddUsing("System.Diagnostics.CodeAnalysis");
                    namespaceCode.AddBeforeCode("");
                    codeBuilder.BuilderDB(db, database, namespaceCode2, tables);

                    List <string> foreignKeys = new List <string>();
                    foreach (var table in tables)
                    {
                        codeBuilder.BuildTable(db, namespaceCode, table, foreignKeys);
                    }

                    bw.Write("code.cs");
                    string code = namespaceCode.Build() + "\r\n" + namespaceCode2.Build();
                    byte[] bs   = System.Text.Encoding.UTF8.GetBytes(code);
                    bw.Write(bs.Length);
                    bw.Write(bs);

                    bw.Write(":end");
                }
            }
            catch (Exception ex)
            {
                new System.IO.BinaryWriter(connectInfo.Response).Write(ex.Message);
            }
        }
Exemplo n.º 7
0
        public void Handle(string originalUrl, HttpConnectInformation connectInfo, ref bool handled)
        {
            if (originalUrl.Contains("/DownLoadSimpleCodeHandler.aspx") == false)
            {
                return;
            }
            handled = true;
            try
            {
                if (connectInfo.Session["user"] == null)
                {
                    throw new Exception("not arrow");
                }

                int databaseid = Convert.ToInt32(connectInfo.Request.Query["databaseid"]);
                using (EJDB db = new EJDB())
                {
                    var database = db.Databases.FirstOrDefault(m => m.id == databaseid);
                    if (database.dllPath == null || database.dllPath.StartsWith("{") == false)
                    {
                        database.dllPath = Newtonsoft.Json.JsonConvert.SerializeObject(new {
                            simple = connectInfo.Request.Query["filepath"],
                            db     = "",
                        });
                    }
                    else
                    {
                        var json = (Newtonsoft.Json.Linq.JToken)Newtonsoft.Json.JsonConvert.DeserializeObject(database.dllPath);
                        json["simple"]   = connectInfo.Request.Query["filepath"];
                        database.dllPath = json.ToString();
                    }
                    db.Update(database);

                    var tables = db.DBTable.Where(m => m.DatabaseID == databaseid).ToList();
                    System.IO.BinaryWriter bw = new System.IO.BinaryWriter(connectInfo.Response);
                    bw.Write("start");

                    var invokingDB = Way.EntityDB.Design.DBHelper.CreateInvokeDatabase(database);
                    IDatabaseDesignService dbservice = Way.EntityDB.Design.DBHelper.CreateDatabaseDesignService((Way.EntityDB.DatabaseType)(int) database.dbType);


                    bw.Write(1);
                    ICodeBuilder codeBuilder = new CodeBuilder();

                    NamespaceCode codeNamespace = new NamespaceCode(database.NameSpace + ".Dtos");
                    codeNamespace.AddBeforeCode("//此代码由工具自动生成,请不要随意修改");
                    codeNamespace.AddUsing("System");
                    codeNamespace.AddUsing("System.Collections.Generic");
                    codeNamespace.AddUsing("System.Linq");
                    codeNamespace.AddUsing("System.Text");
                    codeNamespace.AddBeforeCode("");

                    foreach (var table in tables)
                    {
                        codeBuilder.BuildSimpleTable(db, codeNamespace, table);
                    }

                    bw.Write("code.cs");
                    byte[] bs = System.Text.Encoding.UTF8.GetBytes(codeNamespace.Build());
                    bw.Write(bs.Length);
                    bw.Write(bs);


                    bw.Write(":end");
                }
            }
            catch (Exception ex)
            {
                new System.IO.BinaryWriter(connectInfo.Response).Write(ex.Message);
            }
        }