I have the following code:
using (Context contexto = new Context())
{
List<Cliente> listCliente = contexto.Cliente.Where(x => x.Status == 0).ToList();
}
How do I delete this result from the database? Remembering that I have numerous relationships that I would also like to delete.
Something like:
using (Context contexto = new Context())
{
List<Cliente> listCliente = contexto.Cliente.Where(x => x.Status == 0).ToList();
foreach(Cliente objCliente in lilstCliente)
{
contexto.Cliente.Remove(objCliente);
}
contexto.SaveChanges();
}
When running, it gives the following error:
The relationship could not be changed because one or more of the foreign-key properties are 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.
Instead of:
contexto.Cliente.Remove(objCliente);
I've also tried:
System.Data.Entity.Infrastructure.DbEntityEntry deb = contexto.Entry(entity);
deb.State = EntityState.Deleted;
And it made the same mistake.
Updating the case:
Well, as I have not figured out how to do this cascading exclusion in general, and I need to put this into production, for now I'm treating object by object, and as I probably did not predict all possible relationships, foreign key error, record this error and know that I need to do an extra treatment, just update the service in question.
The object I want to exclude can have multiple relationships, and those relationships can have other relationships, all depending on the object I want to exclude. Ex: I want to delete client, the client has a process, the process has history. That is, if I delete the client, I want both process and process history to be deleted as well.