Hi there
I'm working on a distributed app with a server and a client, where the server exposes services via WCF. The server uses the Entity Framework, and its various methods return EntityObjects.
In the client, I have no references to the server. So in the client, the classes are wholly generated proxies.
I have a delete method in the server. When I pass an object (back) to it for deletion, it does this (stripped of exception handling etc):
public void DeleteCarrier(CarrierDefinition carrier)
{
var container = new WsaEntities();
if (carrier.EntityState == EntityState.Detached)
{
container.CarrierDefinitions.Attach(carrier);
}
container.CarrierDefinitions.DeleteObject(carrier);
container.SaveChanges();
}
Two other tables have foreign keys to CarrierDefinition. One of the FKs is nullable with an ON CASCADE SET NULL constraint, the other has CASCADE DELETE. The above code throws me an exception:
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.
However, if I delete an entity which hasn't been round-tripped in this way, it works as expected:
public void DeleteCarrier(Guid carrierId)
{
var container = new WsaEntities();
var c = container.CarrierDefinitions.Where(cd => cd.Id == carrierId).First();
container.CarrierDefinitions.DeleteObject(c);
container.SaveChanges();
}
Here, the ON CASCADE SET NULL and ON CASCADE DELETE works just fine.
I have inspected the carrier (entity) argument in debug mode, and haven't been able to find anything amiss. Specifically, the entity collections are populated, and contain the related objects. It looks amazingly complete and correct, considering that it has been serialized, then deserialized to a proxy class and vice versa. But somewhere, something just isn't quite right.
I know I can just as well use this method signature and move on, or even keep the signature and use the carrier argument's Id property in place of the carrierId argument. But I'm worried that this will be the first of many problems because something is unsound with the whole approach.
What can I try? Is there anything I should do besides attaching the entity, for example?
I should mention that I'm using the SQL Server Compact Edition v3.5 here, although it doesn't seem to me like that's the problem in this particular case.