EF 6, How to delete an Entity without enforcing cascade delete and satisfying Foreign Key restraints

StackOverflow https://stackoverflow.com/questions/23558037

Pergunta

I'm trying to figure out how to delete an entity without cascade delete

I'm assuming if i do this right, when i delete a related entity (Country, see below), it will set the Country FK in Client to null and the world is all good

Error

The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.Clients_dbo.Countries_CountryId". The conflict occurred in database "JCE", table "dbo.Clients", column 'CountryId'.
The statement has been terminated.

The code i'm using

public class Country : IEntity
{
    [Required,Key]
    public int Id { get; set; }

    [Required,Index]
    public int Code { get; set; }

    [Required]
    public string Name { get; set; }

}

and

public class Client : IEntity
{

    [Required,Key]
    public int Id { get; set; }

    [Required]
    public String Name { get; set; }
    public String Description { get; set; }

    public virtual Country Country { get; set; }

}

I use the following model builder

modelBuilder.Entity<Client>()
    .HasRequired(r => r.Country)
    .WithMany()
    .WillCascadeOnDelete(false);

And use the following code to delete a country

Db.Countries.Attach(country);
Db.Countries.Remove(country);
Db.SaveChanges();

Question

What do i need to do to satisfy my requirements? Also Please let me know if you see any redundancies or oddities with the code i'm using thanks

Foi útil?

Solução

Make your FK constraint optional.

modelBuilder.Entity<Client>()
    .HasOptional(r => r.Country)
    .WithMany()
    .WillCascadeOnDelete(false);

That way it is possible to have a nullable Foreign key.

Your FK will only be set to null if, and only if, your child object is also loaded in EF. So here you have to include your Country entity in when you retrieve your Client entity.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top