score:30
You aren't deleting the object with the remove statement. Instead you are attempting to alter a record and make it an orphan (by setting the foreign key to null). The database has a non-null constraint on that column and prevents you from doing so.
score:3
I use this extension in order not to add a method in DAL just to delete an entity (code taken from http://blogs.msdn.com/b/alexj/archive/2009/06/08/tip-24-how-to-get-the-objectcontext-from-an-entity.aspx):
public static void Delete<T>(this EntityCollection<T> collection, T entityToDelete) where T : EntityObject, IEntityWithRelationships
{
RelationshipManager relationshipManager = entityToDelete.RelationshipManager;
IRelatedEnd relatedEnd = relationshipManager.GetAllRelatedEnds().FirstOrDefault();
if (relatedEnd == null)
{
throw new Exception("No relationships found for the entity to delete. Entity must have at least one relationship.");
}
var query = relatedEnd.CreateSourceQuery() as ObjectQuery;
if (query == null)
{
throw new Exception("The entity to delete is detached. Entity must be attached to an ObjectContext.");
}
query.Context.DeleteObject(entityToDelete);
collection.Remove(entityToDelete);
}
So I then delete an entity like Order.Products.Delete(prod)
.
Constraints to use the extension are:
- Entity must have relationships;
- Entity must be attached to ObjectContext.
score:8
If you make the relationship between child and parent an identifying one then you can remove child entities from the collection. You need to make the child's key a composite key containing the primary id key of the parent. That way EF knows it needs to remove the child.
Identifying relationship basically says if the parent doesn't exist then the child has no meaning. This means EF knows it is safe to delete the child when the relationship is removed.
See this question Identifying Relationship and inserting child entities causes "Cannot insert explicit value for identity column in table" and this one Is it possible to remove child from collection and resolve issues on SaveChanges?
score:11
add context.DeleteObject(recipe)
inside the loop
score:27
http://weblogs.asp.net/zeeshanhirani/archive/2010/07/23/removing-entity-from-a-related-collection.aspx explains exactly what happened to you.
Assuming you have a class design something like this:
Entity Framework will generate the required foreign key columns and add NOT NULL
constraints to them because all Recipes will always be associated with exactly one ControlUnit.
So at runtime you will have objects similar to the following layout:
Now your code comes into play and deleted the relationship between the Recipe objects and their ControlUnit:
Trying to save at this moment, the database does not have a ControlUnit ID to put into the foreign key NOT NULL
column. The current object state violates the class diagram above and cannot be saved to a database layout that has been generated under the assumption that every Recipe is associated with one ControlUnit. This is why the database refuses to save the changes and you see the exception.
This also explains why it works when you uncomment the line deleting the entity: The entity is removed from the database along with its relationship, so no constraints are violated, therefore no exception.
"But I set ON DELETE CASCADE
on the relationship..."
Yes, but that is only triggered on deletion of the object, not on deletion of the relationship. With ON DELETE CASCADE
set, this should work:
controlUnitRepository.DeleteObject(_controlUnit);
// deletes the ControlUnit and all associated Recipe entities
If you want to trigger deletion of the Recipe entities on deletion of their relationship with ControlUnit, your relationship should not be a simple association but rather a composition:
EF does not support this natively, but you can emulate the behaviour using identifying relationships. Once an entity is in an identifying relationship to a parent entity and that relationship is removed, the entity is removed as well. It seems this was your intention from the start. For more information on identifying relationship, see Implementing identifying relationships with EF4 where I implemented identifying relationships with EF4 and have linked to more reading material.
Source: stackoverflow.com
Related Query
- EF 4: Removing child object from collection does not delete it - why?
- Why does my method not run when I attempt to delete a Record from my database using a strongly-typed Delete View?
- Why removing objects from a list with duplicate properties of types double in C# does not give consistent result using different methods?
- LINQ: Select where object does not contain items from list
- How do I delete records from a child collection in LINQ to SQL?
- Includes child and child's objects when the child object is not list or collection
- Collection was modified; enumeration operation may not execute, when trying to delete child records
- Linq join does not include data from child table in Entity Framework
- Why does my code not find directories
- Get a random item from a collection that does not already exist in another collection - LINQ?
- Why this multi linq join code does not work?
- The data source does not support server-side data paging
- Add items to a collection if the collection does NOT already contain it by comparing a property of the items?
- Cannot initialize type '' with a collection initializer because it does not implement 'System.Collections.IEnumerable'
- Expression references a method that does not belong to the mocked object
- Why LINQ to Entities does not recognize the method 'System.String ToString()?
- Why does Resharper suggest that I simplify "not any equal" to "all not equal"?
- linq select items from child collection
- Dude, where's my object? or, Why does Linq not return my object?
- Why does the Linq Cast<> helper not work with the implicit cast operator?
- Why does Single() not return directly when more than one element is found?
- Cannot implement type XYZ with a collection initializer because it does not implement 'System.Collections.IEnumerable'
- Why does not null in LINQ query still return null records?
- Why does EF 5.0 not support this EF 4.x LINQ syntax when compiling to sql?
- Enumerable.Empty<T>().AsQueryable(); This method supports the LINQ to Entities infrastructure and is not intended to be used directly from your code
- Why does Linq not have Head and Tail?
- Why does a GC after a LINQ query free the WhereListIterator but not the Func representing the condition?
- Why does using anonymous type work and using an explicit type not in a GroupBy?
- Select object from nested collection using Linq
- LINQ: why does this query not work on an ArrayList?
More Query from same tag
- Several assignment into one Select
- bool column in where clause - linq/c#
- Comparing two lists and getting higher values
- Issues in converting SQL to LINQ
- Binding data from database to a label control in asp.net
- Adding additional query to return(View)
- Speeding up SQL to Linq ToList
- C# Find best matching element / Simplify query to List
- c# xml element() select element where not defined
- c# Linq `List<Interface>.AddRange` Method Not Working
- How to select first n number of columns from a DataTable
- Identity Filter Linq .Where
- Operator '==' cannot be applied to operands of type 'System.Guid' and 'string' in linq to entity
- C# sorting list by two dates
- C# linq multiple sorts in one clause
- Sort dynamic List<T> for a specific property
- Using query expression vs Seq modules?
- How to write a Lambda Expression to select distinct words from list of sentences
- How to implement SQL where in for entity framework 6
- Complex linq with Entity Framework query
- US States Drop Down List - need State Name Header to Show
- Linq to fetch all records if PageSize is 0
- .NET 4.5, LINQ, Bootstrap tab control, and asp:Repeater
- Sort JSON by one or more properties using Dynamic LINQ
- How to use OrderBy in Linq
- How does this translate to SQL to LINQ?
- How to test post method in fiddler?
- LINQ expression to generate a list of days between two dates
- How to use LINQs Include in SQL
- How to use list.where function with the objects getting casted before getting an IEnumerable