开发者

Add object to collection failed for ColumnCollection of table [name]

I have the following code:

IEnumerable<Table> tables = dbtables.ToList()
                                    .Where(x => x.Name.StartsWith("PartStats"));

 foreach (var tbl in tables)
 {
    Table JoinTable = new Table(db, "ProductMaterial");
    JoinTable.Columns.Add(tbl.Columns[0]);

    string tblName = tbl.Columns[0].Name;
    string script =
                @"ALTER TABLE [dbo].[ProductMaterial]  
                   WITH CHECK ADD  CONSTRAINT [FK_" + tbl.Name +
                "] PRIMARY KEY([" + s;
    string script2 = @"]) REFERENCES [dbo].[" + tbl.Name + "] ([" + tblName + "])" ;
    string newscr = string.Conca开发者_开发百科t(script, script2);
    AddPrimaryKey(tbl, newscr);

This used to work, but now when I run it, I get this error:

"Add object to collection failed for ColumnCollection of table ProductMaterial".

AddPrimaryKey() just executes the script on the SQL Server, and is fine. The problem is in the preceding code to that method call.

The server is on, I am using local admin account for the SQL Server (my windows account is an admin for the SQL Server).

Thanks


Perhaps wrap the call in a check whether the column already exists on the table.

if (!JoinTable.Columns.Contains(tbl.Columns[0].Name)
{
    JoinTable.Columns.Add(tbl.Columns[0]);
}

Could it be that you're trying to add multiple Tables named "ProductMaterial"?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜