I have read everything that I could find and still I couldn't solve my problem. I am using PostgreSQL and I have an abstract class and a child class. I would like that when the parent has been deleted also all related dependencies to be deleted.
Here is how my class looks like:
public abstract class NotificationModel
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public Guid id { get; set; }
public string type { get; set; }
// and other common fileds
public abstract NotificationModel buildObject(JObject json);
}
My child class :
class SmsNotificationModel : NotificationModel
{
public override NotificationModel buildObject(JObject json){return dummyObj;}
public SmsBody Body { get; set; }
public Guid Fk_sms { get; set; }
}
And SmsBody
class SmsBody
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public Guid Id { get; set; }
public List<string> Recipients { get; set; }
public string Route { get; set; }
//edit
public SmsNotificationModel smsNotModel { get; set; }
}
In DbContext:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<SmsNotificationModel>()
.HasOne(em => em.Body)
.WithOne(d => d.smsNotModel)
.HasForeignKey<SmsNotificationModel>(f => f.Fk_sms)
.OnDelete(DeleteBehavior.Cascade);
base.OnModelCreating(modelBuilder);
}
I don't understand what I am doing wrong. The table is marked as a cascade but when I try to drop this it does not work at all. Can somebody give me some tips about how can I set up this.
==== Later Edit
I have a generic repo for removing (template param is NotificationModel abstract class)
public class GenericRepository<T> : IGenericRepository<T> where T :class
{
private readonly ApplicationDbContext _context;
private DbSet<T> table = null;
public GenericRepository(ApplicationDbContext _context) {
this._context = _context;
table = _context.Set<T>();
}
public void Delete(object id){
T existing = table.Find(id);
table.Remove(existing);
}
}
_context.Save()?SmsBodymust have aNotificationproperty, which to call... HasOne(em => em.Body).WithOne(body => body.Notification /* or whatever you call this new property */);. You can read more about this here. Plus, don't forget toAdd-MigrationandUpdate Database.