I am trying to simplify my code and am moving some of the core logic on to the Entity Framework entities themselves (Seems like that is why we have entities that model business logic). Presently entities are pretty much just a bunch of properties and collections.
I am looking at having a function on the entity that removes an item from a collection and adds it to another collection on the entity.
Now the add to the other collection function works perfectly. However the remove - removes the item from the collection however it doesn't delete.
I get:
The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable.
I understand that this is because removing from collection doesn't actually mark for delete and when context save changes occurs it is upset by the key being nulled but not marked for removal. As I am not in a repository and have no access to the context within. How am I supposed to let the context know that this item needs to be deleted?
I thought I was supposed to make sure domain entities encapsulated appropriate business logic. Is this just the wrong thing to be doing? How can I get around this? Should I get around this?
If I use the extension method:
public static ObjectContext GetContext(this IEntityWithRelationships entity)
{
if (entity == null)
throw new ArgumentNullException("entity");
var relationshipManager = entity.RelationshipManager;
var relatedEnd = relationshipManager.GetAllRelatedEnds()
.FirstOrDefault();
if (relatedEnd == null)
throw new Exception("No relationships found");
var query = relatedEnd.CreateSourceQuery() as ObjectQuery;
if (query == null)
throw new Exception("The Entity is Detached");
return query.Context;
}
I can access the context within the entity like this:
var context = this.GetContext() as Entities;
context.events.DeleteObject(event);
This seems hideous but does work. Surely doing this can't be the right way?