Update datatables using relation - c#

I try to update two tables using a relation and table adapters generated in dataset designer. But unable to perform child table update, it is not inserted, the problem is that during child table update the identity column value is unknown.
Table "Users" has primary key and identity column UserId. Table "UserInRoles" has column UserId and foreign key to Users.UserId. Here is my code:
usersTableAdapter.Fill(ds.Users);
userInRolesTableAdapter.Fill(this. ds.UserInRoles);
DataRow userRow = ds.Users.NewRow();
userRow["UserName"] = userName; // and fill other userRow fields.
DataRow userRoleRow = ds.UserInRoles.NewRow();
userRoleRow["RoleId"] = selectedRole; // leave unfilled column "UserId", because I thing the relational update should do it.
userRoleRow.SetParentRow(userRow, ds.Relations["FK_UserInRoles_Users"]);
ds.Users.Rows.Add(userRow);
ds.UserInRoles.Rows.Add(userRoleRow);
tableAdapterManager.UpdateAll(ds);
ds.AcceptChanges();
//usersTableAdapter.Update(ds.Users);
//userInRolesTableAdapter.Update(ds.UserInRoles);
I set both relation type, update rule: cascade, delete rule: cascade, accept rule: none. Refresh the datatable option is selected. On database the foreign key is set to cascade update too, and enforce for replication and enforce foreign key to yes.
What I am doing wrong?
I tried Users.GetChanges() after users table update, but don't get any changes. The only way it works now is to fill again users table after update. Tried update table adapters separately, but then get error violating foreign key.

you have missed to create a datarelation object
here how to do it:
http://msdn.microsoft.com/en-us/magazine/cc188919.aspx

Related

LINQ to Entity : truncate table fails because of foreign key constraint

In my database, I have a parent table and a child table with foreign key pointing to the parent.. at some point I have to clear all rows from both tables.
I used the following code in Entity Framework:
using (MuseumDBEntities db = new MuseumDBEntities())
{
db.Database.ExecuteSqlCommand("truncate table childTable");
db.Database.ExecuteSqlCommand("truncate table parentTable");
}
I get an exception at the second truncate because of foreign key, although I am clearing child table first.
What should I do? Is there another way to delete all rows of both tables?
I don't know if a foreach loop over all rows is practical.
That's SQL server's fault!
You have two ways to achieve your goal:
Drop the foreign keys, then truncate the table and then recreate the foreign key (I don't recommend this solution because it is too much work and usually not worth it)
Instead of Truncate use Delete (I usually use this method)
Your code will look like this:
using (MuseumDBEntities db = new MuseumDBEntities())
{
db.Database.ExecuteSqlCommand("Delete from childTable");
db.Database.ExecuteSqlCommand("Delete from parentTable");
}
Since the two delete statements have no conditions (no where clause), all rows will be deleted from the tables.

Getting Foreign Keys in SQLite Database

I am trying to read in table schemas from an existing database.
I am reading in all of the tables and columns on each table using the .tables and .columns command. The .columns command returns a variable PRIMARY_KEY which lets me know it is a primary key for the table.
My question is how do I know whether a column is a foreign key to another table (and which table it is a foreign key of)?
To get information about the foreign key constraints of a table, use PRAGMA foreign_key_list.

delete data from table with no primary key using EF database first

I am working on EF database first application and I have encounter the situation where delete records from a table which has no primary key.
I have no control over the database and it is not possible to add any key for the DB table.
What is the best approach I can take?
The best approach is ,you need add a primary key.
Why EF need you add a PK?
Because, PK is a only way to identity the row in the table , if not exists a PK , the table may have many same rows(if have PK,it's different,PK is unique,each row will be different),so if your want to delete or update ,which row is your target? if not exists PK ,EF couldn't know how to identity the row ,so you must have PK in the table.
If you can't add one (may be the DB is from customer, you don't have permission), you can change the mapping XML file between EF and DB,To add a relate PK Element for a unique table column.

SQL Server PK and FK always equal value

I have question, how can i insert a new data into a database that the primary key and foreign key is always equal in value?
ex. i entered my name into Name table and that Name table has PK and FK. every time i insert a new data, the FK was empty. i expect that the value of FK is same as the value of PK even they have different field name.
above is my database relationship. every time i insert new data the EventsID pk(Eventstbl) wont copy to EvnetsID FK(Organizationtbl)
The referential integrity does not work as you described. It better suits functionality of the triggers. The purpose of the PK and foreign key constraint is to prevent insertion of data which is not exist in other table as PK. Therefore, if you want to copy data from Eventstbl to Organizationtbl upon inserting a new record to the former, you need to write a trigger for the insertion event of the Eventstbl. Your PK - FK constraint will work like following, when you insert new record to Organizationtbl, it will check Eventstbl table for the corresponding EventsID. If it does not exist, it will not allow you to insert new record to Organizationtbl. I hope it helps.
Well, you can use a trigger in EventsTbl, an after insert / update trigger. So this trigger could insert / update the other table you need. You can use the INSERTED table to catch the new value of the PK. I hope it helps.

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

Categories