How to maintain referential integrity when parents tables keys are changed? - c#

I have created a C# app that makes a clone copy from an MS Access database and migrates the data to another DB server, but that will require changing the primary keys. What is the best way to maintain the referential integrity to the child tables when the parent tables keys are changed?
Thanks,
Andrew

You may already know this but your primary key column values should not be changing, much, if at all. However, that aside, you don't mention what database you are using. But with SQL Server, you can set up FK's to do what is called a cascading update. This means that if a PK value changes, all FK rows in child tables will have the value changed as well.
The following is an article describing this: http://blogs.techrepublic.com.com/datacenter/?p=128

I'm assuming you have autoIncrement set as the datatype on the PK field of an Access table and you want equivalent functionality in your new db.
Import the Access tables into destination tables with numeric, not auto-increment, data types. Then add your RI back between parent and child tables. Then edit your PK field to auto increment.

I did end up using composite primary keys since each time the app makes a clone copy it is a "snapshot" of the entire dataset. I've therefore added a columne called "Revision" and set each table's primary key to Pk = OID + REVISION.
For the child table it should reference the parent table by their primary key, which means the foreign key will also be composite. How do you achieve that relationship in Access? What I have done is in Access 2007 go to "Database Tools" -> "Relationship" and there edit the relationship so that it displays the following:
(parent Oid) 1 <--- many (child parentKey), (parent Revision) 1 <--- many (child Revision)
Please tell me is this is the way to do it. Or if someone can tell me how to achieve that using SQL commands I'll try that too.
Thanks,

Related

The table does not have a primary key defined error

I have two tables that are basically link tables.
So one looks like this;
QueueId
TaskId
the two columns link to a Queues table and a Tasks table.
There is no primary key and i don't believe I need one.
I so try to import it into my .EDMX and I get the warning that
the table does not have a primary key defined but that it's been inferred as a read only table.
Also, the table doesn't show up in the Diagram and there is no model created for it.
I added a primary key and then got errors in my code.
I deleted all tables and did it all again and still the same thing happens with this one table.
The second table that is virtually identical has the same error but does appear in the diagram.
How do I get the first table to show in the diagram and not be read only because I need to delete the associations from time to time.
Thanks
Entity Framework doesn't need association table in the model to work with it.
There should be two navigation properties on either side of the relation - Task has ICollection<Queue> and Queue has ICollection<Task>. To remove association between specific task and queue you either find queue and remove that thask from it's collection, or do the reverse.

C# Entity Framework: Update Query Does not work

I have this simple code : (update value)
I'm trying to update column "c"
using (MaxEntities ctx = new MaxEntities())
{
aa orders = (from order in ctx.aa
select order).First();
orders.c = 22;
ctx.SaveChanges();
}
this is the table :
CREATE TABLE [dbo].[aa](
[a] [int] NULL,
[b] [int] NOT NULL,
[c] [int] NOT NULL
) ON [PRIMARY]
and values inside :
but i get an exception :
The property 'c' is part of the object's key information and cannot be modified.
I'm new to EF.
any help will be much appreciated.
The property 'c' is part of the object's key information and cannot be modified.
That's why you can't edit it. Maybe you need to add id column as a key with identity specified
As explained in another answer EF must uniquely identify every entity. If you don't have PK in the database, EF will infer some key. Key is considered as fixed so if EF inferred c as part of the key (and it did it because it uses all non-nullable non-binary columns) you cannot change its value. Moreover EF takes all tables without primary key as readonly so even if you remove c from the key in the designer and modify c value you will get another exception when you execute SaveChanges.
The reason for the second exception is in the way how EF describes model and the database. When EF inferred key, it did it only for description of your entities and for context's internal needs but not for description of the database. When EF tries to save changes it builds UPDATE statement from database description and without information about real database PK columns it will not be able to identify correct record for update (every update in EF can affect only single record - EF checks ROWCOUNT). This can be solved by cheating EF and updating its database description = by describing some column in the table description as primary key. This leads to multiple problems:
You must have some unique column in the database otherwise this method will not work.
You must edit EDMX manually (as XML) to add this change
You must not use default MS EDMX designer for updating your model from database because it will delete your change
Simple advice: Either use database tables with primary keys or don't use Entity framework.
Primary key missing here. Add primary key in table and it work.
I believe if there's no PK at all, EF uses all of the fields/columns as part of the key info.Here's a nice explanation: by #SteveWilkes of why. But what do your entities look like? The other possibility is that it doesn't have a property because the association is inside a different entity, if this is a foreign key.
EDIT
This got me thinking. There are just going to be situations where you have to work with legacy tables having no PK, even if you would never create such a thing. What about views? EF is a mapper - it has to uniquely identify that record so it infers and defines this key. Yes, you could use stored procedures, but could you also hack the XML and remove the keys from the table definition?
AND EDIT AGAIN
After posting this, I see #Ladislav Mrnka already said a similar idea (cheating EF and updating its database description), so it has been done (WARNING: Consume at your own risk - never tried). Quick google got me this blog with clear instructions:
Close the model designer in Visual Studio if it is still open and re-open the .edmx file in an XML editor
Find the edmx:StorageModels -> Schema -> Entity Container -> EntitySet element that refers to the table in question
On the EntitySet element, rename the store:Schema attribute to Schema
Remove the store:Name attribute altogether
Remove the opening and closing DefiningQuery tags and everything in between them
Save and close the .edmx file
But really, who doesn't like a PK? Can you not add an id?

EntitySet<T> in LINQ to SQL- using it and removing it

I've got a pair of tables in my database. One of which has a primary key (a simple numerical ID), the other has that ID as a foreign key.
The first table has suddenly gained an EntitySet<OtherTable>. If I add a new OtherTable() to this, is it automatically sent to the database, and the ID's linked up, etc, when I use SubmitChanges()?
Secondly, the relationship isn't many-to-one, it's one-to-one, a corresponding entry in the second table is optional and singular. As such, a container like EntitySet isn't really appropriate for this relationship. An OtherTable? would be a more appropriate representation. How can I inform LINQ to SQL of this?
Set Unique = true in the associaton properties. That should adjust it to being 1:1

Inserting Rows in Relationship using a Strongly Typed DataSet

I'm using ADO.NET with a strongly typed dataset in C# (.NET 3.5). I want to insert a new row to two tables which are related in an 1:n relation.
The table Attachments holds the primary key part of the relation and the table LicenseAttachments holds the foreign key part.
AttachmentsDataSet.InvoiceRow invoice; // Set to a valid row, also referenced in InvoiceAttachments
AttachmentsDataSet.AttachmentsRow attachment;
attachment = attachmentsDataSet.Attachments.AddAttachmentsRow("Name", "Description");
attachmentsDataSet.InvoiceAttachments.AddInvoiceAttachmentsRow(invoice, attachment);
Of course when I first update the InvoicesAttachments table, I'll get a foreign key violation from the SQL server, so I tried updating the Attachments table first, which will create the rows, but will remove the attachment association in the InvoiceAttachments table. Why?
How do I solve this problem?
On the relation between the tables, ensure that the "Both Relation and Foreign Key Constraint" is selected and "Update Rule" is set to "Cascade". Combined with the "Refresh the data table" option on the adapter, after you insert your parent row, the updated ID will "Cascade" down the relationships, preventing foreign key violations in your dataset. Your child tables will then be ready to properly insert into the database.
Some things to try:
When you configure the tableadapter, did you click on advanced options, and check on "refresh data table" so that it will retrieve the identity column value?
For me sometimes I either forgot to check it, or it didn't save the configuration correctly because I didn't have my table identity increment/seed set for whatever reason. Are you using identity increment on the table?
You might also consider just re-creating the adapters for those two tables.
Usually when I go back over everything I find it was something stupid on my part.
Lastly, you might consider calling update on the Primary table, then manually grab the primary key value and manually set the value when you insert the child record. If that doesn't make sense let me know and I will post code.
You need to tell your parent table's table-adapter to refresh the
data-table after update operation.
This is how you can do that.
Open the properties of ProgramUserGroupTableAdapter -> Default Select Query -> Advnaced options. and Check the option of Refresh the data table. Save the adapter now. Now when you call update on table-adapter, the data-table will be updated [refreshed] after the update operation and will reflect the latest values from database table. if the primary-key or any coloumn is set to auto-increment, the data-table will have those latest value post recent update.
Now you can Call the update as pug.Update(dsUserGroup.ProgramUserGroup);
Read latest values from the ProgramUserGroup coloumns and assign respective values into the child table before update. This will work exactly the way you want.
alt text http://ruchitsurati.net/files/tds1.png

Edit composite key value using LINQ

I have a table which uses three columns as a composite key.
One of these column values is used as a sequence tracker for ordered related records. When I insert a new record I have to increment the sequence numbers for the related records that come after the new record.
I can do this directly in SQL Server Management Studio, but when I attempt this in LINQ I get the following error:
Value of member 'Sequence' of an object of type 'TableName' changed.
A member defining the identity of the object cannot be changed.
Consider adding a new object with new identity and deleting the existing one instead.
Can anyone suggest a way around this limitation?
(Adding a new record (as suggested by the error message) isn't really an option as the table with the composite key has a relationship with another table.)
Changing primary keys is a "code smell" in my book.
The fix we implemented was as follows
Deleted the relationship that used the composite key
Added autoincrement ID field, set that as primary key
Added Unique contstraint to the three fields that we were previously using as our
Re-created the relationship using the three fields that were previously our primary key
I worked around this by using a SQL stored proc to update one of the primary keys and calling it from LINQ.
I think the compiler is right. The only way of doing this is creating a new record and deleting the old one.
(Adding a new record (as suggested by
the error message) isn't really an
option as the table with the composite
key has a relationship with another
table.)
I think there's no problem with this. Just copy all the fields of your entity, set the new sequence, and set also any relation by just assigning the old EntitySet reference to the new one. I tried this and it updates correctly.
Besides of this, couldn't you just create a new ID column with auto-increment? I agree with #ocdecio. I think changing primary keys is poor design ...
I don't know LINQ, but would this work if you have cascading update defined on the SQL Server for the FK relationships?
Mind, I think using a composite key is a bad idea and changing one is a worse idea. The primary key should not change. Too many things can get broken if the primary key changes. And what do you do when the primary key changes and it is now not unique? If you do this, you will need a way to handle that as well because it will happen.

Categories