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

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.

Related

MariaDB cant insert data with entity framework 5.0

i have a problem with inserting data in my database.
I have three tables which i created with the heideSQL and linked the three tables with foreign key. 1st table (many to one) 2nd table (one to many) 3rd table. when i try now to insert new data with db.SaveChanges(); it throws an insert exception which tells me that he cant match the foreign key because eventually two or more objects have the same primary key. but i just have one ID-Field in each table which is AUTO_INCREMENT. i use the ID-Field of the 2nd table to link in the first and the 3rd one.
could the problem be that everytime i create the new database object for insert that i always add the same object which belongs to the 2nd table to the db-object even it stays the same. same with the object for the 1st table. might that be the mistage and how can i fix this?
the code and the pic of the database are attached. i hope it helps to understand my problem.
Cheers, Only3lue
db.zeichnungs.Add(zeichnung);
db.projekts.Add(projekt);
db.tags.Add(tag);
}
try
{
db.SaveChanges();
} ...

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.

insert data in no identity number column

I have a table in my database.
This table has one column named A, the column is not entity or auto number, unique key or...
I created a model from my db with Entity Framework 4.1.
My code
using (var contex = new testEntities())
{
Table_1 t = new Table_1();
t.A = 1;
contex.Table_1.Add(t);
contex.SaveChanges();
}
I do not want to use the identity number or index in my table.
When I want to insert a row in it it gives me this error:
Unable to update the EntitySet 'Table_1' because it has a DefiningQuery and no
<InsertFunction> element exists in the <ModificationFunctionMapping> element to
support the current operation.
You either have to give the table a primary key (which you don't seem to want to do) or you need to provide a function to tell Entity Framework how data can be inserted into the database.
I would strongly suggest that you put a primary key on your table unless you have a very good reason for not doing this, and in all my years I can't think of many instances when I wanted a table without a primary key.
If you don't want the primary key at all, then you might find this article useful about using Stored Procs for INSERTing data into the database: http://msdn.microsoft.com/en-us/data/gg699321.aspx

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

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,

SqlBulkCopy into table with composite primary key

I'm trying to use SqlBulkCopy to insert new rows into my DB table by manually populating a DataTable w/in my application.
This works fine for all tables except the table that has a composite primary key made up of 3 columns. Whenever I try to SqlBulkCopy anything into this table, I get the following error:
Violation of PRIMARY KEY constraint 'PK_MYCOMPOSITEKEY'. Cannot insert duplicate key in object 'dbo.MyTable'.
The statement has been terminated.
Is this even possible?
I have tried setting up my DataTable's primary keys with the following:
dt.PrimaryKey = new[] {dt.Columns["PKcolumn1"], dt.Columns["PKcolumn2"], dt.Columns["PKcolumn3"]};
but again, no luck.
The problem you have is with the data.
In the input file there is either or both of
a row which has the same data in the e pk columns as you already have in the table
or
The file has at least two rows with the same values of the pk columns
Bulk insert to a staging table. Clean up any duplicate records. Then do an insert using straight SQL. When you write the insert code be sure to limit it to records in the staging table that are not in the prod table.
You should verify your bulk data for copies before you hit the DB, the problem could be there as well (not just clashing with an existing constraint, or record in DB). It does work and it is usually correct to report it.
Nonetheless, the entire show of DataSet or even DataReaders is a messy exercise in mappings, bad typeless design, plenty of unnecessary transformations, allocations, object[] based values, and the entire thing becomes order, type and string dependent mess (something only MS could design and keeps designing). Native OLEDB bulk interfaces on the other hand are much cleaner.

Categories