0
votes

Morning, I used Code First to build my database, and inheritance hierarchy of Table per Type (TPT) approach was implemented. As below is a sample model of my project:

public enum Type
{
    A = 0,
    B = 1
}

public abstract class Device
{
    public int DeviceId { get; set; }
    public Type Type { get; set; }
}

[Table("DeviceA")]
public class DeviceA : Device
{
    public int Value { get; set; }
}

[Table("DeviceB")]
public class DeviceB : Device
{
    public int Value { get; set; }
}

And I have a table, which is related to both A & B. The model is as shown below:

public class Sir
{
    public int SirId { get; set; }

    [Required]
    public virtual DeviceA DeviceA { get; set; }

    public virtual DeviceB DeviceB { get; set; }
}

And the OnModelCreating function as below:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

        modelBuilder.Entity<Sir>()
            .HasRequired(s => s.DeviceA)
            .WithMany()
            .WillCascadeOnDelete(true);

        modelBuilder.Entity<Sir>()
            .HasOptional(s => s.DeviceB)
            .WithMany()
            .WillCascadeOnDelete(false);

        base.OnModelCreating(modelBuilder);
    }

Here comes the problem, when I attempt to delete a device in the superclass. A SQL error prompted:

The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.DeviceA_dbo.Devices_DeviceId". The conflict occurred in database "CodeFirst", table "dbo.DeviceA", column 'DeviceId'.

As far as I understand, according to MSDN documentation in http://msdn.microsoft.com/en-us/data/jj591620.aspx (Under the header section of Enabling Cascade Delete), it states that . If a foreign key on the dependent entity is not nullable, then Code First sets cascade delete on the relationship. If a foreign key on the dependent entity is nullable, Code First does not set cascade delete on the relationship, and when the principal is deleted the foreign key will be set to null.

But still, I fail to cascade delete a record A in the superclass after trying for hours. Please advise. Thanks !

1

1 Answers

0
votes

Try mapping the foreign keys:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{

    modelBuilder.Entity<Sir>()
        .HasRequired(s => s.DeviceA)
        .WithMany()
        .Map(m => m.MapKey("DeviceA_Id"))
        .WillCascadeOnDelete(true);

    modelBuilder.Entity<Sir>()
        .HasOptional(s => s.DeviceB)
        .WithMany()
        .Map(m => m.MapKey("DeviceB_Id"))
        .WillCascadeOnDelete(false);

    base.OnModelCreating(modelBuilder);
}