我的数据库中有三个表:Book,Library和AvailableBooks。 Book表有一个名为“Book_ID”的主键,类似地,Library有一个“Library_ID”主键。这两个字段具有属性AutoNumber,我想在应用程序启动时表中没有记录时重置字段。我是这样做的:
internal void alterBookTable() {
if (isBookTableInitialized) return;
List<Book> booksFromDb = getAllBooks();
if (booksFromDb.Count > 0) return;
OleDbCommand alterTablesCommand = new OleDbCommand("ALTER TABLE Book ALTER COLUMN Book_ID AUTOINCREMENT(100,1)", DbConnection);
alterTablesCommand.ExecuteNonQuery();
isBookTableInitialized = true;
}
除了altersTableCommad:
之外,Library表的更改方式类似 OleDbCommand alterTablesCommand = new OleDbCommand("ALTER TABLE Library ALTER COLUMN Library_ID AUTOINCREMENT(300,1)", DbConnection);
“Book_ID”字段和“Library_ID”字段都在AvailableBooks表中。 Book表中的“Book_ID”与AvailableBooks表中的“Book_ID”之间存在一对多关系,与“Library_ID”类似。
当我运行此应用程序时,我得到“System.Data.OleDb.OleDbException:无法更改字段'Book_ID'。它是一个或多个关系的一部分”
有没有办法保持这种相同的关系,但改变字段,使其与所有表格保持一致?
答案 0 :(得分:1)
以下代码似乎符合您的要求:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
namespace oleDbTest
{
class Program
{
static void Main(string[] args)
{
string myConnectionString;
myConnectionString =
@"Provider=Microsoft.ACE.OLEDB.12.0;" +
@"Data Source=C:\__tmp\books.accdb;";
using (var con = new OleDbConnection())
{
con.ConnectionString = myConnectionString;
con.Open();
using (var cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandText =
"ALTER TABLE AvailableBooks " +
"DROP CONSTRAINT BookAvailableBooks";
cmd.ExecuteNonQuery();
cmd.CommandText =
"ALTER TABLE AvailableBooks " +
"DROP CONSTRAINT LibraryAvailableBooks";
cmd.ExecuteNonQuery();
cmd.CommandText =
"ALTER TABLE Book " +
"ALTER COLUMN Book_ID AUTOINCREMENT(100,1)";
cmd.ExecuteNonQuery();
cmd.CommandText =
"ALTER TABLE Library " +
"ALTER COLUMN Library_ID AUTOINCREMENT(100,1)";
cmd.ExecuteNonQuery();
cmd.CommandText =
"ALTER TABLE AvailableBooks " +
"ADD CONSTRAINT BookAvailableBooks " +
"FOREIGN KEY (Book_ID) REFERENCES Book";
cmd.ExecuteNonQuery();
cmd.CommandText =
"ALTER TABLE AvailableBooks " +
"ADD CONSTRAINT LibraryAvailableBooks " +
"FOREIGN KEY (Library_ID) REFERENCES Library";
cmd.ExecuteNonQuery();
}
con.Close();
}
}
}
}
答案 1 :(得分:0)
你的问题是“MSAccess”,但看起来你正在使用C#。如果要在MSAccess中执行此操作,则需要删除表,重新创建表,然后重新创建关系。 This Microsoft website有一些您可能想要查看的代码。