简体   繁体   English

使用C#问题在访问中添加和删除链接表

[英]Appending and deleting linked tables in access using c# issue

I have a piece of code that goes through all the linked tables and tables in an access database and for every table(all linked in this case) that matches a certain criteria it should add a new table and delete the old. 我有一段代码遍历访问数据库中所有链接的表和表,对于匹配特定条件的每个表(在这种情况下都是链接的),它应该添加一个新表并删除旧表。 The new is on a sql server database and the old the oracle, however this is irrelevant. 新版本位于sql server数据库上,旧版本位于oracle上,但这无关紧要。 The code is: 代码是:

var dbe = new DBEngine();
            Database db = dbe.OpenDatabase(@"C:\Users\x339\Documents\Test.accdb");
            foreach (TableDef tbd in db.TableDefs)
            {
                if (tbd.Name.Contains("CLOASEUCDBA_T_"))
                {
                    useddatabases[i] = tbd.Name;
                    string tablename = CLOASTableDictionary[tbd.Name];
                    string tablesourcename = CLOASTableDictionary[tbd.Name].Substring(6);
                    var newtable = db.CreateTableDef(tablename.Trim());
                    newtable.Connect = "ODBC;DSN=sql server copycloas;Trusted_Connection=Yes;APP=Microsoft Office 2010;DATABASE=ILFSView;";
                    newtable.SourceTableName = tablesourcename;
                    db.TableDefs.Append(newtable);
                    db.TableDefs.Delete(tbd.Name);
                    i++;
                }

            }
            foreach (TableDef tbd in db.TableDefs)
            {
                Console.WriteLine("After loop "+tbd.Name);

            } 

There are 3 linked tables in this database 'CLOASEUCDBA_T_AGENT', 'CLOASEUCDBA_T_CLIENT' and 'CLOASEUCDBA_T_BASIC_POLICY'. 此数据库“ CLOASEUCDBA_T_AGENT”,“ CLOASEUCDBA_T_CLIENT”和“ CLOASEUCDBA_T_BASIC_POLICY”中有3个链接表。 The issue with the code is that it updates the first two tables perfectly but for some unknown reason, it never finds the third. 该代码的问题在于,它完美地更新了前两个表,但是由于某些未知原因,它从未找到第三个表。 Then in the second loop, it prints it out... it seems to just skip over 'CLOASEUCDBA_T_BASIC_POLICY'. 然后在第二个循环中将其打印出来……似乎只是跳过了'CLOASEUCDBA_T_BASIC_POLICY'。 I really dont know why. 我真的不知道为什么。 The weird thing is then that if run the code again, it will change 'CLOASEUCDBA_T_BASIC_POLICY'. 奇怪的是,如果再次运行代码,它将更改为'CLOASEUCDBA_T_BASIC_POLICY'。 Any help would be greatly appreciated. 任何帮助将不胜感激。

Modifying a collection while you are iterating over it can sometimes mess things up. 遍历集合时修改集合有时会使事情变得混乱。 Try using a slightly different approach: 尝试使用稍微不同的方法:

  1. Iterate over the TableDefs collection and build a List (or perhaps a Dictionary ) of the items you need to change. 遍历TableDefs集合,并为您需要更改的项目建立一个List (或者一个Dictionary )。 Then, 然后,

  2. Iterate over the List and update the items in the TableDefs collection. 遍历List并更新TableDefs集合中的项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM