How to delete objects from a list?


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)

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:


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.

asked by anonymous 13.06.2017 / 15:03

1 answer


By default the EntityFramework already does the deletecascade by default, only if you turn it off with the following command it will not do it:

protected override void OnModelCreating(DbModelBuilder modelBuilder)


In your case you have a 1-0:1 relationship so Entityframework does not know what to do when it has a null value, it can not do delete. This is a limit of EntityFramework < 6 and has nothing to do


  • As informed, delete the child records manually.
  • There are several libraries that extend EntityFramework like link try to find something that does this.
  • About the 2 commands you ran In entity 6.0 there is a difference between:



    context.Entry(Cliente).State = EntityState.Deleted;

    When using the first, cascade are enabled, the EF will internally perform the necessary deletions for the child records. By using the second option, EF will not deal with the necessary deletions.

    22.08.2017 / 18:37