SQL Server trigger delete or cascade delete - triggers

First off I haven't done much SQL code before only the basic CRUD, but I'm involved in a project in which I have access to SQL Server and its up to me to write the SQL.
I've been busy looking on stackoverflow for a solution but (being new) it does not make any sense to me.
I'm using SQL Server 2012.
I have the following relationship (with foreign key constraints in place)
Client > Order > OrderItems
Order
Id
ClientId
OrderItems
Id
OrderId
I'm using EF and when I call my delete method on client I need to delete all the the related items in orders and orderitems tables
I need to add a trigger to go and delete orders and orderitems, but I'm not sure how to do this or if a cascade delete (I've heard of) is best?
Anyone have a quick example and advice of how to do this?

For simple situations, use the cascade delete.
If you have more complex requirements, use the triggers, or a stored procedure for your deletions
http://msdn.microsoft.com/en-us/library/aa902684(v=sql.80).aspx

Related

How to add foreign key relationship in Entity Framework?

Click here to see how to do it while using a code first approach. Below the original database first approach question and answer.
I am using Entity Designer to create a database first model. Now I want to create a foreign key relationship between ProductId and ProductId (see below). I looked at the "add new association" but I cannot connect the two items. Can someone more experienced tell me how to accomplish this?
According to Relationships/Associations with the EF Designer, the steps to create a foreign key association are:
Right-click an empty area of the design surface, point to Add New, and select Association….
Fill in the settings for the association in the Add Association dialog.
...being sure to check the Add foreign key properties to the Entity checkbox when filling in the relationship details.
See also: Relationships, Navigation Properties, and Foreign Keys
If you are using the database first approach, it's better to create the foreign key on the database and update the model. Of course, this is true if you can modify the database; if not, you're stuck with the option of creating the referential constraint on the model.
To answer the bonus question:
If you have SQL Management Studio installed then you can very easily use the Database Migration wizard (right click on a database, "Tasks", "Deploy Database to SQL Azure") and from there fill the textboxes with the required information that you get from Azure.
Also, make sure to add your IP to the ignore list in Azure or else you won't be able to upload. This can be done in the Azure webportal.

Transactions in Entity Framework

I need some idea in handling transactions in Entity Framework.
Let's consider a small example.
In my database I have a table A with auto generated identity column id, and I have a table B with a reference key to A(id).
In a scenario where I need to insert data in to both tables A and B, I want to start a transaction. Lets say a new row is inserted into A. I need newly inserted identity (id) value that I need to utilize for B insertion.
Can someone give me lead on handling this situation? Do we need to really utilize transactions in this case?
When you call SaveChanges, the updates are made in a transaction. If one fails, it is all rolled back. See here on msdn. Particularly the "Remarks" section.

EF WillCascadeOnUpdate

Is there a way in ef migrations to set the Foreign GUID key to cascade on update?
If I have two db's with a user table and the same user with different primary keys, I would like to set the primary GUID key of one to the other.
Basically I'm trying to avoid having to create another column between them to check for syncing.
There are two problems in this to solve:
How do get desired behaviour of the database and/or code.
How to get EF Migrations to generate the stuff needed (triggers or whatever) for the solution from point 1.
For the first part, I would look into using a trigger. For the second part, creating the trigger with migrations, it can be done by running a raw sql command in the migration step (you have to use a code based migration).

Change tracking with EF over time?

I'd like to know what is the best practice to track and/or persist changes over time if I use EF. I'd like to get started with EF for a new project. What I need is a kind of change history.
That's how I did it before: If a record was created it was saved with an ID and with the same ID as InvariantID. If the record was updated i marked it as deleted and created a new record with the new values and a new ID but the same InvariantID. Like this I always had my current record but a history of changes as well.
This works perfectly fine for my scenarios. The amount of historical records is not an issue because I use this usually only for data that's not changing very often.
Is this build in EF somehow or what's the best way to get this behavior for EF?
No it is not build into EF and it will not work this way. I even don't think that it is a good approach on the database level because it makes referential integrity very complex.
With EF this will work only if you use following approach:
You will use conditional mapping for your entity - condition will be IsDeleted = 0. It will ensure that only non deleted entities will be used in queries.
You will have mapped stored procedure for delete operation to correctly set IsDeleted = 1 instead of really deleting the record
You will have to manually call DeleteObject to delete your record and after that you will insert new record - the reason is that EF is not able to deal with scenario where entity change its PK value during update.
Your entities will not be able to participate in relations unless you manually rebuild referential integrity with some other stored procedure
You will need stored procedure to query historical (deleted) records

Delete object and all its child objects in Entity Framework?

I've been trying to find the answer to this question here. Several people seem to ask similar things, but I don't get the answers. I have an EF entity with a bunch of child entities (one-to-many relationship). I want to be able to delete the "parent" entity and have all the child entities deleted at the same time.
Some people mention "Cascade Delete" should be set on both EF model and database (Sql Server in my case). The problem is:
I have absolutely no idea how to do this (seems to be implied in those answers that you should know, but sorry...)
I have a feeling I've run into a similar problems before and found an answer somewhere that was simpler than setting this Cascade Delete. I may be wrong, maybe it is the only way, but if there is a simpler solution I'd like to know.
In either case, a clear example of how to get this working would be greatly appreciated!
In SQL Managment Studio go to your database and find the table where there should be a foreign key. Add a foreign key to the table pointing to the other table. I assume you know how to setup a foreign key. In the foreign key setup at the bottom of the dialog window you'll see a Delete property. Set it to Cascade. This will cause any dependent rows to be deleted whenever the parent row is deleted. Then go and update your data model in Visual Studio. Everything should be setup for you now.
Here is some relevant documentation on MSDN. Note though that there appears to be an error in the example. I received the following error from the EDMX designer when using this configuration.
Operations cannot be specified on ends with multiplicity '*'.
You should set the OnDelete property to Cascade for the end will be triggering deletes on the other end.
As an example, in a relationship involving customers and orders where you would like to have a customer's orders deleted along with the customer, you should set the OnDelete property for the Customer role to Cascade.
Note that only objects that have been loaded into the ObjectContext will be affected by a cascading delete. You will be relying on the cascading delete that you set in the database to look after any other records.