0

Trying to achieve foreign key on delete behavior by data annotation. I tried in the following way

Below are my model configuration

 public class Course
    {
        public int CourseId { get; set; }
        public string CourseName { get; set; }
        public int CourseType { get; set; }
        public bool IsActive { get; set; }
        public bool IsDeleted { get; set; }
    }

    public class Staff
    {
        public int StaffId { get; set; }
        public string StaffName { get; set; }
        [Required]
        public int CourseId { get; set; }
        public virtual Course Course { get; set; }
        public bool IsActive { get; set; }
        public bool IsDeleted { get; set; }
    }

When the migration is added it generated below

migrationBuilder.CreateTable(
                name: "Staff",
                columns: table => new
                {
                    StaffId = table.Column<int>(type: "int", nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    StaffName = table.Column<string>(type: "nvarchar(max)", nullable: false),
                    CourseId = table.Column<int>(type: "int", nullable: false),
                    IsActive = table.Column<bool>(type: "bit", nullable: false),
                    IsDeleted = table.Column<bool>(type: "bit", nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Staff", x => x.StaffId);
                    table.ForeignKey(
                        name: "FK_Staff_Courses_CourseId",
                        column: x => x.CourseId,
                        principalTable: "Courses",
                        principalColumn: "CourseId",
                        onDelete: ReferentialAction.Cascade);
                });

Now want to change ondelete behavior (not manually) as required instead of cascade. I know we can achieve it using fluent API but wondering can we achieve it using data annotation ??

Gopi
  • 92
  • 1
  • 10

1 Answers1

1

It's possible in EF Core 7 with the DeleteBehaviorAttribute. If you are not in EF Core 7 then you can use this below code described in more detail here. Otherwise you have to use FluentAPI.

foreach (var relationship in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
{
    relationship.DeleteBehavior = DeleteBehavior.Restrict;
}
NaniSore
  • 74
  • 1
  • 9