Wednesday, March 28, 2012

Scripter & foreign keys

Hey Peeps Smile

I'm having trouble generating scripts for my databases with SMO. Any foreign keys in the base will blow up the code below. The error message says that the target collumn of the foreign key does not exist, which is hogwash. I have tried this on 3-4 different bases with exact same result. I'm 100 million % sure that these db's and foreign keys are ok.

I cant believe MS has relased something with so obvious a problem, so it must be my fault. So my questions are.

1) What's wrong with the code below?
2) Lets says for arguments sake that the problem reported was true, why would SMO even care about that? Im only asking it to script what it finds, not to argue about consistency etc. (I tried with the DriCheck option to false with same result)

/cheers
/Frederic

Server server = new Server("localhost");
Scripter scripter = new Scripter(server);
Database database = new Database(server, "Test");

database.Refresh();

int objectCount = database.Tables.Count;

SqlSmoObject[] objectsToScript = new SqlSmoObject[objectCount];

for( int t = 0; t < objectCount; t++ )
{
objectsToScript[t] = database.Tables[t];
}

scripter.Options.DriForeignKeys = true;

StringCollection output = scripter.Script(objectsToScript);


Hi Frederic,

In the above code, you are using the statement,

Database database = new Database(server, "Test");

this is actually used to create a new database. What you need to do is access an existing database on the server. Use the statement

Database database = server.Databases["Test"];

This should solve your problem.

Thanks,

Kuntal

No comments:

Post a Comment