简体   繁体   中英

Entity Framework Code First - Delete related items from a table

I am using Entity Framework code first.

I have multiple classes that required an audit trail (eg Car, Van). When a change is made to an instance of this class, the audit trial is updated. These classes all inherit from a parent (Vehicle) and they all use a GUID as an ID.

My Audit Trail class has a reference to this GUID and an audit message.

How do I configure my domain objects so that when I delete a Car, all of the corresponding Audit Trail items are deleted? Is there a way to do this in the domain model, do I need to configure this elsewhere, or should I just be cleaning up the Audit Trail repository after every delete operation?

public class Car : Vehicle
{
    public string CarProperty { get; set; }
}

public class Vehicle
{
    public Guid Id { get; set; } = Guid.NewGuid();
    public string ItemName { get; set; }
}

public class AuditTrail
{
    public Guid Id { get; set; } = Guid.NewGuid();

    public string AuditNote { get; set; }

    public Guid VehicleId { get; set; }
}

You have two options:

  1. You can keep you existing AuditTrail class where VehicleId points to either a Car or a Van etc. but without any Foreign key constraint since it will be able to point towards multiple tables in your data base (you will probably want to record which table the AuditTrail is for). This is tidy in that you won't have too many fields, but means that you will need to write code to delete AuditTrails when you delete the corresponding Vehicle.

  2. You can create a separate field for each Table which relates to the AuditTrail (CarId, VanId etc.) and then create a Foreign Key constraint for each relationship with a cascade delete rule which will automatically delete the AuditTrail with the corresponding vehicle. This will mean adding a new field and constraint for each new Vehicle Table you add and creating code to handle all the different types when creating the AuditTrail.

     public class Car: Vehicle { public string CarProperty { get; set; } public IList<AuditTrail> AuditTrails { get; set; } } public class Vehicle { public Guid Id { get; set; } = Guid.NewGuid(); public string ItemName { get; set; } } public class AuditTrail { public Guid Id { get; set; } = Guid.NewGuid(); public string AuditNote { get; set; } [ForeignKey(nameof(CarId))] public Car Car { get; set; } public Guid? CarId { get; set; } }

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