コード例 #1
0
ファイル: DatabaseEditor.xaml.cs プロジェクト: wwwK/EntityDB
        public DatabaseEditor(int projectid, EJ.Databases database)
        {
            InitializeComponent();
            _projectID   = projectid;
            _currentData = database;
            if (_currentData == null)
            {
                _currentData           = new EJ.Databases();
                _currentData.Guid      = Guid.NewGuid().ToString();
                _currentData.ProjectID = projectid;
                _currentData.conStr    = "server=;uid=;pwd=;Database=";
            }

            var           dbtypes = typeof(EJ.Databases_dbTypeEnum).GetFields();
            List <DBType> source  = new List <Forms.DatabaseEditor.DBType>();

            for (int i = 1; i < dbtypes.Length; i++)
            {
                source.Add(new DBType()
                {
                    Name = dbtypes[i].Name, Value = (EJ.Databases_dbTypeEnum)(int) dbtypes[i].GetValue(null)
                });
            }
            cmbDBType.ItemsSource = source;
            root.DataContext      = _currentData;
        }
コード例 #2
0
        public void Create(EJ.Databases database)
        {
            SqlConnectionStringBuilder conStrBuilder = new SqlConnectionStringBuilder(database.conStr);
            var mydbName = conStrBuilder.InitialCatalog;

            conStrBuilder.InitialCatalog = "master";
            IDatabaseService db;

            try
            {
                db = EntityDB.DBContext.CreateDatabaseService(conStrBuilder.ToString(), EntityDB.DatabaseType.SqlServer);

                /*
                 * COLLATE Chinese_PRC_CI_AS ,如果没有这句,linux的sql server中文会乱码
                 * 指定SQL server的排序规则
                 *  Chinese_PRC指的是中国大陆地区,如果是台湾地区则为Chinese_Taiwan
                 *  CI指定不区分大小写,如果要在查询时区分输入的大小写则改为CS
                 *  AS指定区分重音,同样如果不需要区分重音,则改为AI
                 *  COLLATE可以针对整个数据库更改排序规则,也可以单独修改某一个表或者某一个字段的排序规则,指定排序规则很有用,比如用户管理表,需要验证输入的用户名和密码的正确性,一般是要区分大小写的。
                 */
                db.ExecSqlString("if not exists(select [dbid] from sysdatabases where [name]='" + mydbName.ToLower() + "') create database " + mydbName.ToLower() + " COLLATE Chinese_PRC_CI_AS");
            }
            catch
            {
            }

            db = EntityDB.DBContext.CreateDatabaseService(database.conStr, EntityDB.DatabaseType.SqlServer);
            CreateEasyJobTable(db);
            //ado.ExecCommandTextUseSameCon("if not exists(select [dbid] from sysdatabases where [name]='" + txt_databasename.Text + "') create database " + txt_databasename.Text);
        }
コード例 #3
0
ファイル: MySqlDatabaseService.cs プロジェクト: wwwK/EntityDB
        public void Create(EJ.Databases database)
        {
            Pomelo.Data.MySql.MySqlConnectionStringBuilder conStrBuilder = new Pomelo.Data.MySql.MySqlConnectionStringBuilder(database.conStr);
            database.Name          = conStrBuilder.Database;
            conStrBuilder.Database = null;

            IDatabaseService db;

            try
            {
                db = EntityDB.DBContext.CreateDatabaseService(conStrBuilder.ToString(), EntityDB.DatabaseType.MySql);
                db.ExecSqlString("create database if not exists `" + database.Name.ToLower() + "` CHARACTER SET 'utf8' COLLATE 'utf8_general_ci'");
            }
            catch
            {
            }


            //创建必须表
            db = EntityDB.DBContext.CreateDatabaseService(database.conStr, EntityDB.DatabaseType.MySql);
            db.DBContext.BeginTransaction();
            try
            {
                CreateEasyJobTable(db);
                db.DBContext.CommitTransaction();
            }
            catch (Exception ex)
            {
                db.DBContext.RollbackTransaction();
                throw ex;
            }
        }
コード例 #4
0
ファイル: MySqlDatabaseService.cs プロジェクト: wwwK/EntityDB
        public void ChangeName(EJ.Databases database, string newName, string newConnectString)
        {
            throw new Exception("MySql 不支持修改数据库名称");
            var dbnameMatch = System.Text.RegularExpressions.Regex.Match(database.conStr, @"database=(?<dname>(\w)+)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            if (dbnameMatch == null)
            {
                throw new Exception("连接字符串必须采用以下形式server=localhost;User Id=root;password=123456;Database=testDB");
            }
            var db = EntityDB.DBContext.CreateDatabaseService(database.conStr.Replace(dbnameMatch.Value, ""), EntityDB.DatabaseType.MySql);

            db.ExecSqlString(string.Format("RENAME database `{0}` TO `{1}`", database.Name.ToLower(), newName.ToLower()));

            try
            {
                var db2 = EntityDB.DBContext.CreateDatabaseService(newConnectString, EntityDB.DatabaseType.MySql);
                db2.ExecSqlString("select 1");
            }
            catch
            {
                //
                db.ExecSqlString(string.Format("RENAME database `{0}` TO `{1}`", newName.ToLower(), database.Name.ToLower()));
                throw new Exception("连接字符串错误");
            }
        }
コード例 #5
0
        public void ChangeName(EJ.Databases database, string newName, string newConnectString)
        {
            var    dbnameMatch_old = System.Text.RegularExpressions.Regex.Match(database.conStr, @"Data Source=(?<dname>(\w|\:|\\)+)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            var    dbnameMatch     = System.Text.RegularExpressions.Regex.Match(newConnectString, @"Data Source=(?<dname>(\w|\:|\\)+)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            string newfilepath     = dbnameMatch.Groups["dname"].Value;
            string oldfilepath     = dbnameMatch_old.Groups["dname"].Value;

            System.IO.File.Move(oldfilepath, newfilepath);
        }
コード例 #6
0
ファイル: ImportSchema.xaml.cs プロジェクト: wwwK/EntityDB
        internal ImportSchema(List <string> tablenames, int targetDatabaseID, EJ.Databases source)
        {
            InitializeComponent();
            _source           = source;
            _targetDatabaseID = targetDatabaseID;

            list.ItemsSource = tablenames;
            list.SelectAll();
            list.Focus();
        }
コード例 #7
0
ファイル: CodeBuilder.cs プロジェクト: wwwK/EntityDB
        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))));
        }
コード例 #8
0
        public void Drop(EJ.Databases database)
        {
            SqlConnectionStringBuilder conStrBuilder = new SqlConnectionStringBuilder(database.conStr);
            var mydbName = conStrBuilder.InitialCatalog;

            conStrBuilder.InitialCatalog = "master";

            var db = EntityDB.DBContext.CreateDatabaseService(conStrBuilder.ToString(), EntityDB.DatabaseType.SqlServer);

            db.ExecSqlString("if exists(select [dbid] from sysdatabases where [name]='" + mydbName.ToLower() + "') drop database " + mydbName.ToLower());
        }
コード例 #9
0
ファイル: MySqlDatabaseService.cs プロジェクト: wwwK/EntityDB
        public void Drop(EJ.Databases database)
        {
            Pomelo.Data.MySql.MySqlConnectionStringBuilder conStrBuilder = new Pomelo.Data.MySql.MySqlConnectionStringBuilder(database.conStr);
            database.Name          = conStrBuilder.Database;
            conStrBuilder.Database = null;

            var db = EntityDB.DBContext.CreateDatabaseService(conStrBuilder.ToString(), EntityDB.DatabaseType.MySql);

            db.ExecSqlString("drop database if exists `" + database.Name.ToLower() + "`");
            db.DBContext.Dispose();
        }
コード例 #10
0
ファイル: DatabaseSchema.xaml.cs プロジェクト: wwwK/EntityDB
        public DatabaseSchema(EJ.Databases database)
        {
            InitializeComponent();
            _target             = database;
            _currentData        = new EJ.Databases();
            _currentData.conStr = "server=;uid=;pwd=;Database=";

            var           dbtypes = typeof(EJ.Databases_dbTypeEnum).GetFields();
            List <DBType> source  = new List <DBType>();

            for (int i = 1; i < dbtypes.Length; i++)
            {
                source.Add(new DBType()
                {
                    Name = dbtypes[i].Name, Value = (EJ.Databases_dbTypeEnum)(int) dbtypes[i].GetValue(null)
                });
            }
            cmbDBType.ItemsSource = source;
            root.DataContext      = _currentData;
        }
コード例 #11
0
        public void Drop(EJ.Databases database)
        {
            string constr = database.conStr;
            var    m      = Regex.Match(database.conStr, @"data source=(?<f>(\w|:|\\|\/|\.)+)", RegexOptions.IgnoreCase);

            if (m != null && m.Length > 0)
            {
                string filename = m.Groups["f"].Value;
                if (filename.StartsWith("\"") || filename.StartsWith("\'"))
                {
                    filename = filename.Substring(1, filename.Length - 2);
                }
                if (System.IO.File.Exists(filename))
                {
                    System.IO.File.Delete(filename);
                }
            }
            else
            {
                throw new Exception("无法从连接字符串获取数据库文件路径");
            }
        }
コード例 #12
0
        public void ChangeName(EJ.Databases database, string newName, string newConnectString)
        {
            string constr = database.conStr;

            constr = Regex.Replace(database.conStr, @"database=(\w)+", "database=master", RegexOptions.IgnoreCase);
            //throw new Exception(constr);
            var db = EntityDB.DBContext.CreateDatabaseService(constr, EntityDB.DatabaseType.SqlServer);
            {
                db.ExecSqlString("exec sp_renamedb '" + database.Name.ToLower() + "','" + newName.ToLower() + "'");

                try
                {
                    var db2 = EntityDB.DBContext.CreateDatabaseService(newConnectString, EntityDB.DatabaseType.SqlServer);
                    db2.ExecSqlString("select 1");
                }
                catch
                {
                    //
                    db.ExecSqlString("exec sp_renamedb '" + newName.ToLower() + "','" + database.Name.ToLower() + "'");
                    throw new Exception("连接字符串错误");
                }
            }
        }
コード例 #13
0
ファイル: CodeBuilder.cs プロジェクト: wwwK/EntityDB
        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));
            }
        }
コード例 #14
0
        static void Test(EJ.Databases dbconfig)
        {
            IDatabaseDesignService dbservice = EntityDB.Design.DBHelper.CreateDatabaseDesignService((EntityDB.DatabaseType)(int) dbconfig.dbType);

            EntityDB.IDatabaseService db = null;
            dbservice.Drop(dbconfig);
            try
            {
                dbservice.Create(dbconfig);
                db = EntityDB.DBContext.CreateDatabaseService(dbconfig.conStr, (EntityDB.DatabaseType)(int) dbconfig.dbType);

                List <EJ.DBColumn> allColumns = new List <EJ.DBColumn>();
                List <EntityDB.Design.IndexInfo> allindexes = new List <EntityDB.Design.IndexInfo>();

                #region CreateTable
                if (true)
                {
                    EJ.DBTable tableUser = new EJ.DBTable();
                    tableUser.Name = "User";

                    allColumns.Add(new EJ.DBColumn()
                    {
                        IsPKID          = true,
                        CanNull         = false,
                        Name            = "Id",
                        dbType          = "int",
                        IsAutoIncrement = true,
                    });
                    allColumns.Add(new EJ.DBColumn()
                    {
                        Name         = "Name",
                        dbType       = "varchar",
                        length       = "50",
                        defaultValue = "a'b,c"
                    });

                    CreateTableAction _CreateTableAction = new CreateTableAction(tableUser, allColumns.ToArray(), allindexes.ToArray());
                    _CreateTableAction.Invoke(db);

                    DeleteTableAction _delaction = new DeleteTableAction(tableUser.Name);
                    _delaction.Invoke(db);

                    //再次创建
                    _CreateTableAction.Invoke(db);
                }
                #endregion

                allColumns.Clear();
                allindexes.Clear();
                allColumns.Add(new EJ.DBColumn()
                {
                    IsPKID          = true,
                    CanNull         = false,
                    Name            = "Id",
                    dbType          = "int",
                    IsAutoIncrement = true,
                });
                allColumns.Add(new EJ.DBColumn()
                {
                    Name         = "C1",
                    dbType       = "varchar",
                    length       = "50",
                    defaultValue = "a'b,c"
                });
                allColumns.Add(new EJ.DBColumn()
                {
                    Name         = "C2",
                    dbType       = "varchar",
                    length       = "50",
                    defaultValue = "abc"
                });
                allColumns.Add(new EJ.DBColumn()
                {
                    Name         = "C3",
                    dbType       = "int",
                    defaultValue = "8"
                });
                allColumns.Add(new EJ.DBColumn()
                {
                    Name   = "Text1",
                    dbType = "text",
                });
                //索引
                allindexes.Add(new EntityDB.Design.IndexInfo()
                {
                    ColumnNames = new string[] { "C1" },
                    IsUnique    = true,
                });
                allindexes.Add(new EntityDB.Design.IndexInfo()
                {
                    ColumnNames = new string[] { "C2", "C3" },
                });


                EJ.DBTable table = new EJ.DBTable();
                table.Name = "Test";

                #region CreateTable
                if (true)
                {
                    CreateTableAction _CreateTableAction = new CreateTableAction(table, allColumns.ToArray(), allindexes.ToArray());
                    _CreateTableAction.Invoke(db);

                    foreach (var c in allColumns)
                    {
                        c.ChangedProperties.Clear();
                        c.BackupChangedProperties.Clear();
                    }

                    checkColumns(dbservice, db, table.Name, allColumns, allindexes);
                }
                #endregion

                #region 测试自增长id
                if (true)
                {
                    Way.EntityDB.CustomDataItem dataitem = new EntityDB.CustomDataItem("test", "id", null);
                    dataitem.SetValue("c1", "C1");
                    dataitem.SetValue("c2", "C2");
                    dataitem.SetValue("c3", 3);
                    db.Insert(dataitem);
                    if (dataitem.GetValue("id") == null)
                    {
                        throw new Exception("测试自增长id失败");
                    }
                    db.ExecSqlString("delete from test");
                }
                #endregion

                #region ChangeTable1
                if (true)
                {
                    EJ.DBColumn[] newcolumns = new EJ.DBColumn[2];
                    newcolumns[0] = (new EJ.DBColumn()
                    {
                        Name = "N0",
                        dbType = "varchar",
                        length = "30",
                        defaultValue = "t'b"
                    });
                    newcolumns[1] = (new EJ.DBColumn()
                    {
                        Name = "N1",
                        dbType = "int",
                        defaultValue = "18"
                    });


                    EJ.DBColumn[] changedColumns = new EJ.DBColumn[2];
                    changedColumns[0]              = allColumns.FirstOrDefault(m => m.Name == "C3");
                    changedColumns[0].Name         = "C3_changed";
                    changedColumns[0].dbType       = "varchar";
                    changedColumns[0].defaultValue = "1'a";
                    changedColumns[0].CanNull      = false;
                    changedColumns[0].length       = "88";


                    changedColumns[1] = allColumns.FirstOrDefault(m => m.Name == "Id");
                    changedColumns[1].IsAutoIncrement = false;
                    changedColumns[1].IsPKID          = false;
                    changedColumns[1].CanNull         = true;



                    EJ.DBColumn[] deletecolumns = new EJ.DBColumn[1];
                    deletecolumns[0] = allColumns.FirstOrDefault(m => m.Name == "C2");

                    allColumns.Remove(deletecolumns[0]);

                    allindexes.Clear();
                    allindexes.Add(new EntityDB.Design.IndexInfo()
                    {
                        ColumnNames = new string[] { "N0", "C3_changed" },
                        IsUnique    = true,
                        IsClustered = true
                    });

                    var otherColumns = (from m in allColumns
                                        where changedColumns.Contains(m) == false
                                        select m).ToArray();

                    new ChangeTableAction(table.Name, "Test2", newcolumns, changedColumns, deletecolumns, otherColumns, allindexes.ToArray())
                    .Invoke(db);
                    table.Name = "Test2";
                    allColumns.AddRange(newcolumns);

                    foreach (var c in allColumns)
                    {
                        c.ChangedProperties.Clear();
                        c.BackupChangedProperties.Clear();
                    }
                    checkColumns(dbservice, db, table.Name, allColumns, allindexes);
                }
                #endregion

                #region ChangeTable2
                if (true)
                {
                    EJ.DBColumn[] newcolumns     = new EJ.DBColumn[0];
                    EJ.DBColumn[] changedColumns = new EJ.DBColumn[1];
                    changedColumns[0] = allColumns.FirstOrDefault(m => m.Name == "Id");
                    changedColumns[0].IsAutoIncrement = true;
                    changedColumns[0].IsPKID          = true;
                    changedColumns[0].CanNull         = false;


                    EJ.DBColumn[] deletecolumns = new EJ.DBColumn[0];

                    var otherColumns = (from m in allColumns
                                        where changedColumns.Contains(m) == false
                                        select m).ToArray();

                    new ChangeTableAction(table.Name, "Test3", newcolumns, changedColumns, deletecolumns, otherColumns, allindexes.ToArray())
                    .Invoke(db);
                    table.Name = "Test3";
                    allColumns.AddRange(newcolumns);

                    foreach (var c in allColumns)
                    {
                        c.ChangedProperties.Clear();
                        c.BackupChangedProperties.Clear();
                    }

                    checkColumns(dbservice, db, table.Name, allColumns, allindexes);
                }
                #endregion
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (db != null)
                {
                    db.DBContext.Dispose();
                }
            }
        }
コード例 #15
0
ファイル: DatabaseItemNode.cs プロジェクト: wwwK/EntityDB
 public DatabaseItemNode(DatabaseNode parent, EJ.Databases db) : base(parent)
 {
     this.Database = db;
     bind();
 }
コード例 #16
0
ファイル: CodeBuilder.cs プロジェクト: wwwK/EntityDB
        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();
        }
コード例 #17
0
        public static EntityDB.IDatabaseService CreateInvokeDatabase(EJ.Databases databaseConfig)
        {
            string conStr = databaseConfig.conStr;

            return(EntityDB.DBContext.CreateDatabaseService(conStr, (EntityDB.DatabaseType)Enum.Parse(typeof(EntityDB.DatabaseType), databaseConfig.dbType.ToString())));
        }
コード例 #18
0
        public void Create(EJ.Databases database)
        {
            var db = EntityDB.DBContext.CreateDatabaseService(database.conStr, EntityDB.DatabaseType.Sqlite);

            CreateEasyJobTable(db);
        }
コード例 #19
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());
        }