Mike
Mike

Reputation: 23

Migration doesn't apply on all foreign keys the ON CASCADE DELETE behavior

I am using Entity Framework Core 5 and I am testing the table relationships. Using these 2 classes as entities

public class Absenta
{
    public int id { get; set; }
    public DateTime dataAbsemta { get; set; }
    public bool Motivata { get; set; }

    public string UserID { get; set; }
    public ApplicationUser User { get; set; }

    public int TrainingID { get; set; }
    public Training Training { get; set; }
}

public class Training
{
    public int TrainingID { get; set; }

    [DisplayName("Training")]
    public string Name { get; set; }

    public string FilePath { get; set; }

    [DisplayName("Clasa")]
    public string NumeClasa { get; set; }

    [DisplayName("Sala")]
    public string NumeSala { get; set; }

    [DisplayName("Data incepere : ")]
    [DataType(DataType.Date)]
    public DateTime DataInceput { get; set; }

    [DisplayName("Data sfarsit  : ")]
    [DataType(DataType.Date)]
    public DateTime DataSfarsit { get; set; }

    public ICollection<Absenta> absente { get; set; }
}

This is the generated query :

CONSTRAINT [PK_Absente] 
    PRIMARY KEY CLUSTERED ([id] ASC),
CONSTRAINT [FK_Absente_AspNetUsers_UserID] 
    FOREIGN KEY ([UserID]) REFERENCES [dbo].[AspNetUsers] ([Id]),
CONSTRAINT [FK_Absente_Traininguri_TrainingID] 
    FOREIGN KEY ([TrainingID]) REFERENCES [dbo].[Traininguri] ([TrainingID]) 
            ON DELETE CASCADE

Migration works perfectly, creating the tables and foreign keys, but for the UserID foreign key it does not apply ON DELETE CASCADE behavior by default.

Is there a way I can set it as default from the class? I am trying to avoid setting it manually for every table.

Upvotes: 0

Views: 279

Answers (1)

Mike
Mike

Reputation: 23

Figured out the solution. All you have to do is use the [Required] data annotation :

[Required]
public string UserID { get; set; }

public ApplicationUser User { get; set; }

Upvotes: 0

Related Questions