Delete object and all its child objects in Entity Framework? - 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.

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.

optimistic concurrency exception was handled by the user code

I'm using MVC4 with Entity Framework 4.1.
Initially we have created an Ado.net entity model from database. In the .edmx file, some of the tables that are in the database are not visible as they dont posses the primary key on particular table.
As our project is moving forward, we need to update to one of the log tables which dont have a primary key field.
So, we modified our .edmx file instead of modifying in the database. our client asked us not to modify the database fields. we have modified the .edmx and created a pk on one of the exisiting field in the table(say tbl_log table).
we are trying to update the tbl_log. But it gives an error message as Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.
I've seen much of questions in stack overflow and also googled a bit, but could not find any solution.
Even i've tried refreshing the ObjectStateManager entries but it still points to the same error.
Here is my code
tbl_log log = new tbl_log();
Entity.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Modified);
log.LoginId = strLoginId;
log.Password = strPassword;
log.IPAddress = strIpAddress;
log.Date_Time = DateTime.Parse(DateTime.Now.ToString());
log.sessionId = new Guid(strSessionId);
Entity.AddTotbl_log(log);
Entity.SaveChanges();// optimistic concurrency error
Please help
Thanks,
Karthik
Your model must represent the database schema. If you add a PK to the model it should exist in the database as well, otherwise you will get errors. It's generally bad practice to not have a PK on any table, even if the table is an audit log table.
What the exception is telling you is that the object tracker cannot determine if the state of the object has changed since the last call to the database. This is because the PK you have set is still 0 even after the framework has sent the insert/update query.
Unfortunately there is no good way to work around this. I would suggest (as I think Microsoft does) to add a primary key column to every table in your database.
EDIT - From comments
As the PK is used to track the object, if you have set the PK to have a StoreGenerationPattern of Identity in your model it will be expecting the value to change. When it doesn't change then it will throw the error your are seeing. Try changing the StoreGenerationPattern to None as then EF won't be expecting your faux-PK to change

Coredata delete rule confusion, xcode

I have a Core Data relationship between two entities, which is like this:
Entity A Entity B
aRelationship <-------------->> bRelationship
With the delete rule set to cascade.
Maybe I have this wrong, but I thought that if the delete rule for both of these relationships was set to "Cascade", then when did the following...
[context deleteObject:EntityA];
...it would also delete all the of the Entity B's associated with it. However when I log all of my entity B's it would seem that I am mistaken.
Could someone please shed some light on my confusion?
Thank you very much.
While it's not immediately apparent in the graphical data model editor each recipocal relationship i.e. each
<-->
...is really two separate relationship each with its own delete rule. Delete rules are activate when an object of the entity with the delete rule is deleted.
So, if in the data model editor you have two entities Alpha and Beta with a relationship:
Alpha.betas<-->>Beta.alpha
… then you really have two relationships like so:
Alpha.betas--(delete rule)-->>Beta.alpha
Beta.alpha--(delete rule)-->Alpha.betas
You never want to set up a delete rule like this:
Alpha.betas--(cascade)-->>Beta.alpha
Beta.alpha--(cascade)-->Alpha.betas
… because deleting any one Beta instance will delete the associate Alpha object which will trigger the deletion of all related Beta objects. Depending on the details of your data model, a reciprocal cascade can delete a big chunk of you data by accident.
What you really want is:
Alpha.betas--(cascade)-->>Beta.alpha
Beta.alpha--(nullify)-->Alpha.betas
Now, when you delete the Alpha object, it will delete all associated Beta objects.
When a cascade is blocked, it is usually a problem with a required relationship. Can't tell for certain without details of the data model.
It depends on what delete rules are you using.
Here is what Apple said in their document:
"When you delete a managed object it is important to consider its
relationships and in particular the delete rules specified for the
relationships. If all of a managed object's relationship delete rules
are Nullify, then for that object at least there is no additional work
to do (you may have to consider other objects that were at the
destination of the relationship—if the inverse relationship was either
mandatory or had a lower limit on cardinality, then the destination
object or objects might be in an invalid state). If a relationship
delete rule is Cascade, then deleting one object may result in the
deletion of others. If a rule is Deny, then before you delete an
object you must remove the destination object or objects from the
relationship, otherwise you will get a validation error when you save.
If a delete rule is No Action, then you must ensure that you take
whatever steps are necessary to ensure the integrity of the object
graph."
The link of “Relationship Delete Rules.”: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreData/Articles/cdRelationships.html#//apple_ref/doc/uid/TP40001857-SW1

Entity Framework - Foreign key constraints not added for inherited entity

It appears to me that a strange phenomenon is occurring with inherited entities (TPT) in EF4.
I have three entities.
1. Asset
2. Property
3. Activity
Property is a derived-type of Asset.
Property has many activities (many-to-many)
When modeling this in my EDMX, everything seems fine until I try to insert a new Property into the database. If the property does not contain any Activity, it works, but all hell breaks loose when I add some new activities to the new Property.
As it turns out after 2 days of crawling the web and fiddling around, I noticed that in the EF store (SSDL) some of the constraints between entities were not picked up during the update process.
Property_Activity table which links properties and activities show only
one constraint
FK_Property_Activity_Activity but
FK_Property_Activity_Property was
missing.
I knew this is an Entity Framework anomoly because when I switched the relationship in the database to:
Asset <--> Asset_Activity <--> Activity
After an update, all foreign key constraints are picked up and the save is successful, with or without activities in the new property.
Is this intended or a bug in EF?
How do I get around this problem?
Should I abandon inheritance altogether?
Not a but but a poor visual designer.
Its generally best to simply manage the Entity XML by hand.
No inheritance works well for many situations.
Basically I use the update from database in the visual designer but knowing that the designer has its quirks. I have simply used the update from database to stub out the basics of what I want. Then I go into the Entity XML my self and clean it up the way I want. Just of note Complex types are a pain with the designer. If you plan to use complex types get ready to learn your Entity XML well.

Delete an object and all of its related entities in Entity Framework

Does anyone know how to delete an object and all of its related entities inside of EF without manually traversing the object graph and deleting each one?
For example, I've got SalesOrder and SalesOrderDetails with a 1:N relationship between them. When I delete a SalesOrder, I want all SalesOrderDetails to be deleted automatically.
Is this possible in EF?
You should not be doing this in the Entity Framework. All popular relational databases support ON CASCADE DELETE on foreign keys which is a lot more efficient as well. I suggest you just go with that.
in this article, Alex Jamese (who post his answer), has a complete article on the topic.
Link
The EF is responsible for the correctness of the ObjectContext after SaveChanges(). So the EF attempts to synchronize the ObjectContext, with the expected database state after the expected cascade in the database.
A tell tale sign of this is that if you open up something like SqlProfiler, you will notice the EF issuing DELETE requests for dependent entities that it knows about (i.e. that are loaded in the ObjectContext) when a principal is deleted.
Essentially what is happening here is that the Entity Framework expects that deleting the principal in the database, will delete all it’s dependents in the database. So it issues, what should be, a redundant DELETE to request itself so the dependents already loaded are deleted from the ObjectContext.
The key thing to note is that the EF does not retrieve all the dependent entities and issue deletes for them: It only deletes dependents that are already in memory.