I'm using entity framework 5 model first.
I have some entities in my model and most of them have one-to-many relationships with "no action" foreign key constraint on delete and update.
But I'm still able to delete father and child objects with no errors (on EF4 I used to get an exception warning that I cannot delete an object because there's another referencing it)
Part of the code generated by EF5 model first:
...
... Create all tables...
...
... Create all foreign key constraints ...
...
-- Creating foreign key on [TEstTela_ID] in table 'TEstPermissao'
ALTER TABLE [dbo].[TEstPermissao]
ADD CONSTRAINT [FK_TEstTelaTEstPermissao]
FOREIGN KEY ([TEstTela_ID])
REFERENCES [dbo].[TEstTela]
([ID])
ON DELETE NO ACTION ON UPDATE NO ACTION;
....
Delete Object Code:
...
EstContextDB CurrentContext = new EstContextDB(); // inherits from DbContext
CurrentContext.Set<TEstTela>().Remove(currentTEstTelaEntity);
CurrentContext.SaveChanges(); /* Exception should be thrown here
because at least one TEstPermissao object references this
currentTEstTelaEntity but it still delete the object without
errors or exceptions, and plus the TEstPermissao object
that references this currentTEstTelaEntity gets its reference as 'null' */
The problem doesn't have to do with cascading delete. You try to delete the parent TEstTelaEntity and EF sets the foreign key from the child TEstPermissao to this parent TEstTelaEntity to null (apparently the relationship is optional) and then sends an UPDATE statement for the child and a DELETE statement for the parent to the database. If cascading delete would kick in the child would be deleted as well, not only the parent. The result is consistent and valid: You just have a TEstPermissao entity in the database now without any reference to a TEstTelaEntity.
The foreign key is set to null only in the case that the child is loaded and attached to the context when you delete the parent. Otherwise you would indeed get the exception about a constraint violation you are expecting. (I believe this difference between attached vs. detached children is the same in EF 4 and EF 5.)
If you really don't want to delete a parent as long as it has any children, check with appropriate code if the parent has children or not in order to decide if Remove should be called.
Related
I have an optional relationship between Table A and Table B where A is the parent and B is the optional child. If I have only A loaded in my DbContext SQL Server will throw me an error that I cannot delete A because of a relationship with B, this is what I want.
However if I have A and the relation to B loaded in the DbContext Entity Framework will set the relationship on B to null which prevents the error from SQL Server. How can I prevent Entity Framework from setting my relationship to null when deleting the parent A?
I want the error to happen as I want to prevent deletion of A when a relationship exists, I don't want Entity Framework to 'fix' the issue for me.
I have a DBFirst EntityFramework 6.1 solution that i'm trying to generate off of. When i add a table that only contains two foreign keys the table is turned into two associations and I can not directly access the table anymore. This is neat for navigation in the code but makes it a pain in the ass to delete records from the table.
Is there a way to prevent this behavior and gain direct access to the table as an entity?
For example i am unable to remove an entry in the association because i get this error
The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.
For example here is how my database sees the structure.
Here is how it appears in entity framework. Notice that the CorporateDataShareVisible table is missing and instead two new associations are created.
The CorporateDataShareVisible table should be able to be deleted and added to at will but any changes i make seem to stop it from working.
Add a primary key to your table that has only foreign keys. EF uses the primary key to keep track internally of the element. Without a primary key it doesnt know which element was modified and how to send that back to your RDBMS.
I prefer surrogate keys i.e auto incrementing integers.
You can also add the primary key by making it a composite key of both the foreign keys
I receive the fore mentioned error when trying to delete an entity.
This entity has a foreign key to a list table, but I can delete the DB entry without a problem from Heidi MySql client.
I'm trying to clear the child entities, but when i call SaveChanges on the context, it throws the mentioned error.
nquote_orderheaders header = portalDb.nquote_orderheaders.Single(f => f.QuoteOrderNumber == id);
header.nquote_orderlines.Clear();
portalDb.SaveChanges();
portalDb.nquote_orderheaders.Remove(header);
portalDb.SaveChanges();
Using .Clear() on a navigation property doesn't remove them from the database, it only clears your collection in your code. You need to iterate over your orderlines to remove them one by one.
Another possibility is to enable cascading delete feature, which allows child entities removal if parent entity is removed.
You can remove an item from a database using EF by using the following two methods.
EntityCollection.Remove Method
ObjectContext.DeleteObject Method
The first is on the EntityCollection and the second on the ObjectContext.
When should each be used?
Is one prefered over the other?
Remove() returns a bool and DeleteObject() returns void.
It's not generally correct that you can "remove an item from a database" with both methods. To be precise it is like so:
ObjectContext.DeleteObject(entity) marks the entity as Deleted in the context. (It's EntityState is Deleted after that.) If you call SaveChanges afterwards EF sends a SQL DELETE statement to the database. If no referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.
EntityCollection.Remove(childEntity) marks the relationship between parent and childEntity as Deleted. If the childEntity itself is deleted from the database and what exactly happens when you call SaveChanges depends on the kind of relationship between the two:
If the relationship is optional, i.e. the foreign key that refers from the child to the parent in the database allows NULL values, this foreign will be set to null and if you call SaveChanges this NULL value for the childEntity will be written to the database (i.e. the relationship between the two is removed). This happens with a SQL UPDATE statement. No DELETE statement occurs.
If the relationship is required (the FK doesn't allow NULL values) and the relationship is not identifying (which means that the foreign key is not part of the child's (composite) primary key) you have to either add the child to another parent or you have to explicitly delete the child (with DeleteObject then). If you don't do any of these a referential constraint is violated and EF will throw an exception when you call SaveChanges - the infamous "The relationship could not be changed because one or more of the foreign-key properties is non-nullable" exception or similar.
If the relationship is identifying (it's necessarily required then because any part of the primary key cannot be NULL) EF will mark the childEntity as Deleted as well. If you call SaveChanges a SQL DELETE statement will be sent to the database. If no other referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.
I am actually a bit confused about the Remarks section on the MSDN page you have linked because it says: "If the relationship has a referential integrity constraint, calling the Remove method on a dependent object marks both the relationship and the dependent object for deletion.". This seems unprecise or even wrong to me because all three cases above have a "referential integrity constraint" but only in the last case the child is in fact deleted. (Unless they mean with "dependent object" an object that participates in an identifying relationship which would be an unusual terminology though.)
If you really want to use Deleted, you'd have to make your foreign keys nullable, but then you'd end up with orphaned records (which is one of the main reasons you shouldn't be doing that in the first place). So just use Remove()
ObjectContext.DeleteObject(entity) marks the entity as Deleted in the context. (It's EntityState is Deleted after that.) If you call SaveChanges afterwards EF sends a SQL DELETE statement to the database. If no referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.
EntityCollection.Remove(childEntity) marks the relationship between parent and childEntity as Deleted. If the childEntity itself is deleted from the database and what exactly happens when you call SaveChanges depends on the kind of relationship between the two:
A thing worth noting is that setting .State = EntityState.Deleted does not trigger automatically detected change. (archive)
I don't want to use foreign key association to CompanyType (member that will hold the foreign key id) but prefer to use navigation property. So I removed the CompanyTypeId.
I get this exception that relates the relationship between entity Company and CompanyType:
Error 5: The element 'Principal' in
namespace
'http://schemas.microsoft.com/ado/2008/09/edm'
has incomplete content. List of
possible elements expected:
'PropertyRef' in namespace
'http://schemas.microsoft.com/ado/2008/09/edm'.
How can I remove those id's from the POCOs without getting the exception?
This is the difference between Foreign key association and Independent association. Both associations use navigation properties but only Foreign key association uses FK property as well. You can either remove them globally as #Robbie mentioned or you can change the type manually for selected relation.
Select the relation in entity framework designer
In properties remove Referential constraints
Go to Mapping window and map the relation
Here is the screen shot from one of my testing application with one-to-many relation between Order and OrderLine entities:
As you can see there is no OrderId in the OrderLine entity and referential constraints of the relation are empty. Also mapping of the relation is specified.
BUT you can't never remove Id from CompanyType. Ids (PKs) are mandatory. You can only change its accessibility in its properties.
When you imported in your Model from your DB you are asked if you want to:
"Include Foreign key columns in the model"
you need to switch this off.