tags:

views:

99

answers:

1

Hi,

I want to create relationships in my SQL Server database using C#.

I have this code:

   foreach (ForeignKey fk in table.ForeignKeys)
                {
                    if (!table.ForeignKeys.Contains("ProductMaterial"))
                }

                table.ForeignKeys.Add(
                     new ForeignKey(
                        new Table(database, 
                                  "ProductMaterial"), 
                                  "ProductMaterial" ));
                DataRelation relation = new DataRelation(
                        "ProductMaterial", new DataColumn(), )

"table" is from a Tables collection in the database, and the database comes from a databases collection in the server instance. I have the condition reversal because I want to add a relationship obviously where one does not exist so I am looking for the absence of an FK.

However, I also have the DataRelation line. Can I just add an FK and that'll be the relationship? Or should I add both an FK and a datarelation object?

Thanks

+1  A: 

First of all, just to be clear (and hopefully you already know this), this code will not create anything in the database... All you are affecting is the structure and relationships between the tables in the ADO.Net DataSet object, which exists only in memory in the process space you are running this code in.

But having said that, adding the Foreign Key just establishes a constraint. This means that it prevents new records from being added to that dataTable with values in the FK field that do not exist in the other table. This is not the same as adding a relationship. A relationship estanlishes the Parent-Child thingy (redundant to call it a relationship here ) which allows other .Net objects like Grids etc, to render the data in a hierarchical manner.

So yes, if you want both you need to add both.

Charles Bretana
Thanks. Yeah I am aware that this does not persist the changes to the db. I have omitted the code which is not immediately relevant to the problem and hence cut that out (As well as the code to get the correct database).
dotnetdev
kewl,, the first sentence in question led me to mention that point explicitly, sorry for being pedantic... ...
Charles Bretana
No problem, I should have stated that I am omitting code anyway.
dotnetdev