Cascade deletes

Mar 13, 2014 at 3:57 PM
Edited Mar 13, 2014 at 3:58 PM
Tom
Help please.

I have two tables Person and Telephone
If I delete a person it does not set the person id in telephone as null or delete telephone.
         var person = context.People.FirstOrDefault(x => x.Name == PersonName);
            context.People.Remove(person);
            context.SaveChanges();
The reverse engineering code first has generated the following
public partial class Person
{
    public Person()
    {
        this.Telephones = new List<Telephone>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Telephone> Telephones { get; set; }
}
public partial class Telephone
{
    public int Id { get; set; }
    public Nullable<int> Idperson { get; set; }
    public string Number { get; set; }
    public virtual Person Person { get; set; }
}
   public PersonMap()
    {
        // Primary Key
        this.HasKey(t => t.Id);

        // Properties
        this.Property(t => t.Name)
            .IsRequired()
            .IsFixedLength()
            .HasMaxLength(25);

        // Table & Column Mappings
        this.ToTable("Person");
        this.Property(t => t.Id).HasColumnName("Id");
        this.Property(t => t.Name).HasColumnName("Name");
    }

   public TelephoneMap()
    {
        // Primary Key
        this.HasKey(t => t.Id);

        // Properties
        this.Property(t => t.Number)
            .IsRequired()
            .IsFixedLength()
            .HasMaxLength(10);

        // Table & Column Mappings
        this.ToTable("Telephone");
        this.Property(t => t.Id).HasColumnName("Id");
        this.Property(t => t.Idperson).HasColumnName("Idperson");
        this.Property(t => t.Number).HasColumnName("Number");

        // Relationships
        this.HasOptional(t => t.Person)
            .WithMany(t => t.Telephones)
            .HasForeignKey(d => d.Idperson);

    }
}
Coordinator
Mar 16, 2014 at 10:38 PM
There are two things that you need to change to get the Telephone record(s) to delete when deleting a person.

1: You need to include the Telephones when retrieving the person.
var person = context.People.Include(x => x.Telephones).FirstOrDefault(x => x.Name == PersonName);
2: You need to include WillCascadeOnDelete in your TelephoneMap.
// Relationships
this.HasOptional(t => t.Person)
    .WithMany(t => t.Telephones)
    .HasForeignKey(d => d.Idperson)
    .WillCascadeOnDelete(true);