简体   繁体   中英

Cascade delete with optional records in Entity Framework

I'm trying to develop an ASP.net MVC application with Entity Framework and in last about 8 hours, i'm trying to fix something without a success. I have 3 models, Overhour , Accounting and Vacation . Overhour is the parent model, once we create an Overhour , we can create an Accounting or Vacation record with it for one time. We don't need to create one, so we can have an Overhour without an Accounting or Vacation . Important thing is, when we delete an Overhour , we should delete both Accountings and Vacations (if they exist).

I'm using code first, i tried it with Data Annotations but it seems when you can't do that with optional models so i'm using Fluent Api now. Here is the thing i'm using for relation between an Overhour and Accounting :

modelBuilder.Entity<Overhour>()
.HasOptional<Accounting>(s => s.Accounting)
.WithOptionalPrincipal()
.WillCascadeOnDelete(true);

Even if i use CodeFirst, i use a plugin to create model diagrams for testing purposes and model looks fine too (i guess):

Diagram (it seems i can't include the image directly)

As i understand, it says "Cascade on End1Delete". So when i delete an Overhour , accounting record should gets deleted too, but it's not working, it just sets it to null.

Another thing is, i'm not sure which one is the parent. I mean, should i have an Overhour model like this:

class Overhour {
    ...
    public int AccountingId { get; set; }
    public virtual Accounting Accounting { get; set; }
}

Or something like this:

class Overhour {
    ...
    public virtual Accounting Accounting { get; set; }
}

Or maybe i should include this properties to Accounting model? Like this:

class Accounting {
    ...
    public virtual Overhour Overhour { get; set; }
}

Maybe i need to do both?

I'm so confused, any ideas?

Thanks

I was able to get cascade delete with optional records to work using this:

public class Overhour
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public virtual Guid Id { get; set; }
}

public class Accounting
{
    [ForeignKey("Overhour")]
    public virtual Guid Id { get; set; }

    public virtual Overhour Overhour { get; set; }
}

public class Vacation
{
    [ForeignKey("Overhour")]
    public virtual Guid Id { get; set; }

    public virtual Overhour Overhour { get; set; }
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Accounting>()
        .HasRequired(accounting => accounting.Overhour)
        .WithOptional()
        .WillCascadeOnDelete(true);

    modelBuilder.Entity<Vacation>()
        .HasRequired(vacation => vacation.Overhour)
        .WithOptional()
        .WillCascadeOnDelete(true);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM