예제 #1
0
        void Database_AfterInsert(object sender, Way.EntityDB.DatabaseModifyEventArg e)
        {
            EJDB db = sender as EJDB;

            if (db == null)
            {
                return;
            }
            if (e.DataItem is EJ.InterfaceModulePower)
            {
                //子module都加入了权限,parent module也应该有权限
                var data   = (EJ.InterfaceModulePower)e.DataItem;
                var module = db.InterfaceModule.FirstOrDefault(m => m.id == data.ModuleID);
                if (module != null && module.ParentID != 0)
                {
                    var parentModule = db.InterfaceModule.FirstOrDefault(m => m.id == module.ParentID);
                    if (parentModule != null && db.InterfaceModulePower.Count(m => m.ModuleID == parentModule.id && m.UserID == data.UserID) == 0)
                    {
                        var newdata = new EJ.InterfaceModulePower()
                        {
                            ModuleID = parentModule.id,
                            UserID   = data.UserID,
                        };
                        db.Insert(newdata);
                    }
                }
            }
        }
예제 #2
0
        /// <summary>
        /// 生成一般的model类
        /// </summary>
        /// <param name="db"></param>
        /// <param name="nameSpace"></param>
        /// <param name="table"></param>
        /// <returns></returns>
        public string[] BuildSimpleTable(EJDB db, string nameSpace, EJ.DBTable table)
        {
            var columns = db.DBColumn.Where(m => m.TableID == table.id).ToList();

            string[] codes = new string[1];
            codes[0] = BuildSimpleTable(db, nameSpace, table, columns);
            return(codes);
        }
예제 #3
0
        void Database_BeforeDelete(object sender, Way.EntityDB.DatabaseModifyEventArg e)
        {
            if (e.DataItem is EJ.DLLImport)
            {
                if (LoginUser.Role.GetValueOrDefault().HasFlag(EJ.User_RoleEnum.管理员) == false)
                {
                    throw new Exception("你没有权限");
                }
            }
            else if (e.DataItem is EJ.Databases)
            {
                if (LoginUser.Role.GetValueOrDefault().HasFlag(EJ.User_RoleEnum.管理员) == false)
                {
                    throw new Exception("你没有移除数据库的权限");
                }
            }
            else if (e.DataItem is EJ.DBModule || e.DataItem is EJ.Databases || e.DataItem is EJ.Project || e.DataItem is EJ.TableInModule || e.DataItem is EJ.DBTable || e.DataItem is EJ.DBColumn)
            {
                if (LoginUser.Role.GetValueOrDefault().HasFlag(EJ.User_RoleEnum.数据库设计师) == false)
                {
                    throw new Exception("你没有修改数据表的权限");
                }
            }

            EJDB db = sender as EJDB;

            if (db == null)
            {
                return;
            }
            if (e.DataItem is EJ.DBModule)
            {
                if (LoginUser.Role.GetValueOrDefault().HasFlag(EJ.User_RoleEnum.数据库设计师) == false)
                {
                    throw new Exception("你没有修改数据表的权限");
                }
                beforeDelete_IDBModule(db, (EJ.DBModule)e.DataItem);
            }
            else if (e.DataItem is EJ.InterfaceModule)
            {
                if (LoginUser.Role.GetValueOrDefault().HasFlag(EJ.User_RoleEnum.数据库设计师) == false)
                {
                    throw new Exception("你没有修改数据表的权限");
                }
                beforeDelete_InterfaceModule(db, (EJ.InterfaceModule)e.DataItem);
            }
            else if (e.DataItem is EJ.DBTable || e.DataItem is EJ.DBColumn)
            {
                if (LoginUser.Role.GetValueOrDefault().HasFlag(EJ.User_RoleEnum.数据库设计师) == false)
                {
                    throw new Exception("你没有修改数据表的权限");
                }
            }
            else if (e.DataItem is EJ.Databases)
            {
                var databaseid = ((EJ.Databases)e.DataItem).id.GetValueOrDefault();
            }
        }
예제 #4
0
        internal static string GetDesignData(EJDB db, EJ.Databases databaseObj)
        {
            var dt = db.Database.SelectDataSet("select actionid as [id],type,content,databaseid from designhistory where databaseid=" + databaseObj.id + " order by [actionid]");

            dt.Tables[0].TableName = databaseObj.dbType.ToString();
            dt.DataSetName         = databaseObj.Guid;
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(dt);

            return(Convert.ToBase64String(GZip(System.Text.Encoding.UTF8.GetBytes(json))));
        }
예제 #5
0
        static void beforeDelete_InterfaceModule(EJDB db, EJ.InterfaceModule item)
        {
            //删除子模块
            var items = db.InterfaceModule.Where(m => m.ParentID == item.id).ToList();

            foreach (var t in items)
            {
                db.Delete(t);
            }

            var items2 = db.InterfaceInModule.Where(m => m.ModuleID == item.id).ToList();

            foreach (var t in items2)
            {
                db.Delete(t);
            }
        }
예제 #6
0
        void outputDesigns(StringBuilder result, EJDB db, EJ.Databases databaseObj)
        {
            DesignData data = new DesignData();

            data.Database = databaseObj;
            data.Modules  = db.DBModule.Where(m => m.DatabaseID == databaseObj.id).ToArray();
            data.Tables   = db.DBTable.Where(m => m.DatabaseID == databaseObj.id).ToArray();
            var tableids = data.Tables.Select(m => m.id.Value).ToArray();

            data.TableInModules  = db.TableInModule.Where(m => tableids.Contains(m.TableID.Value)).ToArray();
            data.IDXIndexes      = db.IDXIndex.Where(m => tableids.Contains(m.TableID.Value)).ToArray();
            data.DBDeleteConfigs = db.DBDeleteConfig.Where(m => tableids.Contains(m.TableID.Value)).ToArray();
            data.DBColumns       = db.DBColumn.Where(m => tableids.Contains(m.TableID.Value)).ToArray();
            data.classproperties = db.classproperty.Where(m => tableids.Contains(m.tableid.Value)).ToArray();
            string json    = Newtonsoft.Json.JsonConvert.SerializeObject(data);
            string content = Convert.ToBase64String(GZip(System.Text.Encoding.UTF8.GetBytes(json)));

            for (int i = 0; i < content.Length; i += 200)
            {
                int len = Math.Min(content.Length - i, 200);
                result.AppendLine(content.Substring(i, len));
            }
        }
예제 #7
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);
        }
예제 #8
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
                {
                }
            }
        }
예제 #9
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);
        }
예제 #10
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();
        }
예제 #11
0
        public void Handle(string originalUrl, HttpConnectInformation connectInfo, ref bool handled)
        {
            if (originalUrl.Contains("/DownloadTableData.aspx") == false)
            {
                return;
            }
            handled = true;

            if (connectInfo.Session["user"] == null || ((EJ.User)connectInfo.Session["user"]).Role.GetValueOrDefault().HasFlag(EJ.User_RoleEnum.数据库设计师) == false)
            {
                return;
            }

            var tableids = connectInfo.Request.Query["tableids"].ToJsonObject <int[]>();

            System.IO.BinaryWriter bw = new System.IO.BinaryWriter(connectInfo.Response);
            using (EJDB db = new EJDB())
            {
                int tid        = tableids[0];
                var dbtable    = db.DBTable.FirstOrDefault(m => m.id == tid);
                var database   = db.Databases.FirstOrDefault(m => m.id == dbtable.DatabaseID);
                var invokingDB = DBHelper.CreateInvokeDatabase(database);
                {
                    string[] tableNames = new string[tableids.Length];
                    int[]    rowCounts  = new int[tableids.Length];
                    for (int i = 0; i < tableids.Length; i++)
                    {
                        int tableid = tableids[i];
                        dbtable       = db.DBTable.FirstOrDefault(m => m.id == tableid);
                        tableNames[i] = dbtable.Name;
                        string sql = $"select count(*) from {invokingDB.FormatObjectName(dbtable.Name)}";
                        rowCounts[i] = Convert.ToInt32(invokingDB.ExecSqlString(sql));
                    }
                    bw.Write(Newtonsoft.Json.JsonConvert.SerializeObject(tableNames));
                    bw.Write(Newtonsoft.Json.JsonConvert.SerializeObject(rowCounts));

                    for (int i = 0; i < tableids.Length; i++)
                    {
                        int tableid = tableids[i];
                        dbtable = db.DBTable.FirstOrDefault(m => m.id == tableid);
                        string sql = $"select * from {invokingDB.FormatObjectName(dbtable.Name)}";
                        invokingDB.ExecuteReader((reader) => {
                            Dictionary <string, object> data = new Dictionary <string, object>();
                            for (int j = 0; j < reader.FieldCount; j++)
                            {
                                string key   = reader.GetName(j);
                                object value = reader[j];
                                if (value != null && value != DBNull.Value)
                                {
                                    data[key] = value;
                                }
                            }
                            if (data.Count > 0)
                            {
                                bw.Write(dbtable.Name);
                                bw.Write(Newtonsoft.Json.JsonConvert.SerializeObject(data));
                            }
                            return(true);
                        }, sql);
                    }
                    bw.Write(":end");
                }
            }
        }
예제 #12
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);
            }
        }
        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(tables.Count * 1);
                    ICodeBuilder codeBuilder = new CodeBuilder();


                    foreach (var table in tables)
                    {
                        string[] codes = codeBuilder.BuildSimpleTable(db, database.NameSpace, table);
                        for (int i = 0; i < codes.Length; i++)
                        {
                            bw.Write(table.Name + "_" + i + ".cs");
                            byte[] bs = System.Text.Encoding.UTF8.GetBytes(codes[i]);
                            bw.Write(bs.Length);
                            bw.Write(bs);
                        }
                    }


                    bw.Write(":end");
                }
            }
            catch (Exception ex)
            {
                new System.IO.BinaryWriter(connectInfo.Response).Write(ex.Message);
            }
        }
예제 #14
0
        static string BuildSimpleTable(EJDB db, string nameSpace, EJ.DBTable table, List <EJ.DBColumn> columns)
        {
            var           pkcolumn    = columns.FirstOrDefault(m => m.IsPKID == true);
            StringBuilder result      = new StringBuilder();
            StringBuilder enumDefines = new StringBuilder();


            result.Append(@"

    /// <summary>
	/// "     + table.caption + @"
	/// </summary>
    public class " + table.Name + @" :Way.Lib.DataModel
    {

        /// <summary>
	    /// 
	    /// </summary>
        public  " + table.Name + @"()
        {
        }

");

            foreach (var column in columns)
            {
                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);
                string att      = ",DbType=\"" + column.dbType;
                if (string.IsNullOrEmpty(column.length))
                {
                    if (column.dbType.Contains("char"))
                    {
                        att += "(50)";
                    }
                }
                else
                {
                    if (column.dbType.Contains("char"))
                    {
                        att += "(" + column.length + ")";
                    }
                }
                att += "\"";
                if (column.IsPKID == true)
                {
                    //,AutoSync= AutoSync.OnInsert ,IsPrimaryKey=true,IsDbGenerated=true
                    att += " ,IsPrimaryKey=true";
                }
                if (column.IsAutoIncrement == true)
                {
                    att += ",IsDbGenerated=true";
                }
                if (column.CanNull == false)
                {
                    att += ",CanBeNull=false";
                }

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

                        enumDefines.Append(@"
/// <summary>
/// 
/// </summary>
public enum " + table.Name + "_" + column.Name + @"Enum:int
{
    
");
                        StringBuilder enumComments = new StringBuilder();
                        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)
                                {
                                    enumComments.AppendLine("/// " + code.Substring(2));
                                }
                            }
                            else
                            {
                                enumDefines.Append(@"
/// <summary>
" + enumComments + @"/// </summary>
");
                                enumComments.Clear();
                                enumDefines.AppendLine(code);
                            }
                        }
                        enumDefines.Append("}\r\n");

                        dataType = "System.Nullable<" + 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>")
                        {
                            eqString = eqString + "m";
                        }
                        else if (dataType == "System.Nullable<float>")
                        {
                            eqString = eqString + "f";
                        }
                        else if (dataType == "System.Nullable<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;
                    }
                }


                result.Append(@"
        " + dataType + @" _" + column.Name + eqString + @";
        /// <summary>
        /// " + column.caption + @"
        /// </summary>
        public virtual " + dataType + @" " + column.Name + @"
        {
            get
            {
                return this._" + column.Name + @";
            }
            set
            {
                if ((this._" + column.Name + @" != value))
                {
                    var original = this._" + column.Name + @";
                    this._" + column.Name + @" = value;
                    this.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);
                        if (column.TableID == table.id)
                        {
                            result.Append(@"
        public virtual " + foreign_table.Name + @" " + pro.name + @" { get; set; }
");
                        }
                        else
                        {
                            //与其他表一对一
                            result.Append(@"
        public virtual " + foreign_table.Name + @" " + pro.name + @" { get; set; }
");
                        }
                    }
                    else
                    {
                        //与其他表多对一
                        result.Append(@"
        public virtual ICollection<" + foreign_table.Name + @"> " + pro.name + @" { get; set; }
");
                    }
                }
                catch
                {
                }
            }

            result.Append("}}\r\n");

            result.Insert(0, @"namespace " + nameSpace + @"{
" + enumDefines);

            return(result.ToString());
        }
예제 #15
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
                {
                }
            }
        }
예제 #16
0
        public void Handle(string originalUrl, HttpConnectInformation connectInfo, ref bool handled)
        {
            if (originalUrl.Contains("/ImportTableData.aspx") == false)
            {
                return;
            }
            handled = true;

            if (connectInfo.Session["user"] == null || ((EJ.User)connectInfo.Session["user"]).Role.GetValueOrDefault().HasFlag(EJ.User_RoleEnum.数据库设计师) == false)
            {
                return;
            }
            try
            {
                int databaseid = Convert.ToInt32(connectInfo.Request.Query["dbid"]);
                System.IO.BinaryReader reader = new System.IO.BinaryReader(connectInfo.Request.Body);
                var tableNames = reader.ReadString().ToJsonObject <string[]>();

                using (EJDB ejdb = new EJDB())
                {
                    var database   = ejdb.Databases.FirstOrDefault(m => m.id == databaseid);
                    var invokingDB = DBHelper.CreateInvokeDatabase(database);
                    { //不要开事物,大数据太慢
                        try
                        {
                            if (connectInfo.Request.Query["clearDataFirst"] == "1")
                            {
                                foreach (var tableName in tableNames)
                                {
                                    invokingDB.AllowIdentityInsert(tableName, true);
                                    invokingDB.ExecSqlString("delete from [" + tableName + "]");
                                }
                            }

                            Dictionary <string, string> pkNames = new Dictionary <string, string>();
                            for (int i = 0; i < tableNames.Length; i++)
                            {
                                var tableName = tableNames[i];
                                var db_table  = ejdb.DBTable.FirstOrDefault(m => m.Name == tableName);
                                if (db_table == null)
                                {
                                    throw new Exception(string.Format("找不到{0}数据表定义", tableName));
                                }
                                var  pkcolumn      = ejdb.DBColumn.FirstOrDefault(m => m.TableID == db_table.id && m.IsPKID == true);
                                bool hasAutoColumn = ejdb.DBColumn.Count(m => m.TableID == db_table.id && m.IsAutoIncrement == true) > 0;
                                pkNames[tableName] = pkcolumn.Name;

                                if (pkcolumn == null)
                                {
                                    throw (new Exception(string.Format("{0}-{1}没有设置主键", db_table.caption, db_table.Name)));
                                }
                            }

                            while (true)
                            {
                                string _tablename = reader.ReadString();
                                if (_tablename == ":end")
                                {
                                    break;
                                }
                                string pkname = null;
                                if (pkNames.ContainsKey(_tablename))
                                {
                                    pkname = pkNames[_tablename];
                                }

                                Dictionary <string, object> data = reader.ReadString().ToJsonObject <Dictionary <string, object> >();
                                CustomDataItem newDataItem;

                                if (pkname != null && data.ContainsKey(pkname))
                                {
                                    if (Convert.ToInt32(invokingDB.ExecSqlString($"select count(*) from {invokingDB.FormatObjectName(_tablename)} where {invokingDB.FormatObjectName(pkname)}=@p0", data[pkname])) > 0)
                                    {
                                        newDataItem = new CustomDataItem(_tablename, pkname, data[pkname]);
                                        foreach (var item in data)
                                        {
                                            newDataItem.SetValue(item.Key, item.Value);
                                        }

                                        invokingDB.Update(newDataItem);
                                        continue;
                                    }
                                }

                                newDataItem = new CustomDataItem(_tablename, pkname, null);
                                foreach (var item in data)
                                {
                                    newDataItem.SetValue(item.Key, item.Value);
                                }
                                invokingDB.Insert(newDataItem);
                            }
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                        finally
                        {
                            foreach (var tableName in tableNames)
                            {
                                invokingDB.AllowIdentityInsert(tableName, false);
                            }
                        }
                    }
                }
                connectInfo.Response.Write("ok\r\n");
            }
            catch (Exception ex)
            {
                connectInfo.Response.Write($"{ex.Message}\r\n");
            }
        }
예제 #17
0
        public string BuilderDB(EJDB db, EJ.Databases databaseObj, string nameSpace, List <EJ.DBTable> tables)
        {
            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)
                {
                    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 + "没有定义主键");
                        }
                        codestrs.Append(@"
                    var items" + i + @" = (from m in db." + delDBTable.Name + @"
                    where m." + relaColumn.Name + @" == deletingItem.id
                    select new " + nameSpace + @"." + delDBTable.Name + @"
                    {
                        " + rela_pkcolumn.Name + @" = m." + rela_pkcolumn.Name + @"
                    });
                    while(true)
                    {
                        var data2del = items" + i + @".Take(100).ToList();
                        if(data2del.Count() ==0)
                            break;
                        foreach (var t in data2del)
                        {
                            db.Delete(t);
                        }
                    }
");
                    }

                    _Database_deleteCodes.Append(@"
                    if (e.DataItem is " + nameSpace + @"." + t.Name + @")
                    {
                        var deletingItem = (" + nameSpace + @"." + t.Name + @")e.DataItem;
                        " + codestrs + @"
                    }
");
                }
            }


            StringBuilder result = new StringBuilder();

            result.Append(@"
namespace " + nameSpace + @".DB{
    /// <summary>
	/// 
	/// </summary>
    public class " + databaseObj.Name + @" : Way.EntityDB.DBContext
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name=""connection""></param>
        /// <param name=""dbType""></param>
        public " + databaseObj.Name + @"(string connection, Way.EntityDB.DatabaseType dbType): base(connection, dbType)
        {
            if (!setEvented)
            {
                lock (lockObj)
                {
                    if (!setEvented)
                    {
                        setEvented = true;
                        Way.EntityDB.DBContext.BeforeDelete += Database_BeforeDelete;
                    }
                }
            }
        }

        static object lockObj = new object();
        static bool setEvented = false;
 

        static void Database_BeforeDelete(object sender, Way.EntityDB.DatabaseModifyEventArg e)
        {
            var db =  sender as " + nameSpace + ".DB." + databaseObj.Name + @";
            if (db == null)
                return;

" + _Database_deleteCodes + @"
        }

        /// <summary>
	    /// 
	    /// </summary>
        /// <param name=""modelBuilder""></param>
         protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
   ");

            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));
                }
                result.AppendLine("modelBuilder.Entity<" + nameSpace + @"." + t.Name + @">().HasKey(m => m." + pkcolumn.Name + ");");
            }
            result.AppendLine("}");

            foreach (var t in tables)
            {
                result.Append(@"
        System.Linq.IQueryable<" + nameSpace + @"." + t.Name + @"> _" + t.Name + @";
        /// <summary>
        /// " + t.caption + @"
        /// </summary>
        public virtual System.Linq.IQueryable<" + nameSpace + @"." + t.Name + @"> " + t.Name + @"
        {
             get
            {
                if (_" + t.Name + @" == null)
                {
                    _" + t.Name + @" = this.Set<" + nameSpace + @"." + t.Name + @">();
                }
                return _" + t.Name + @";
            }
        }
");
            }
            result.Append("\r\n");


            var dt = db.Database.SelectDataSet("select * from __action where databaseid=" + databaseObj.id + " order by [id]");

            dt.Tables[0].TableName = databaseObj.dbType.ToString();
            dt.DataSetName         = databaseObj.Guid;
            string json    = Newtonsoft.Json.JsonConvert.SerializeObject(dt);
            string content = Convert.ToBase64String(GZip(System.Text.Encoding.UTF8.GetBytes(json)));

            result.AppendLine("protected override string GetDesignString(){System.Text.StringBuilder result = new System.Text.StringBuilder(); ");
            result.AppendLine("result.Append(\"\\r\\n\");");
            for (int i = 0; i < content.Length; i += 200)
            {
                int len = Math.Min(content.Length - i, 200);
                result.AppendLine("result.Append(\"" + content.Substring(i, len) + "\");");
            }
            result.AppendLine("return result.ToString();}");
            result.Append("}}\r\n");
            return(result.ToString());
        }