How can I solve on delete no action or on update no action problen when using code-first in Entity Framework with authentication

Viewed 835

I'm creating a project for hospital automation in user authentication and using code-first in Entity Framework.

Here my Hospital entity:

    public int Id { get; set; }
    public string Name { get; set; }
    public string PhoneNumber { get; set; }

Here my Clinic entity:

    public int Id { get; set; }
    public string Name { get; set; }

And my HospitalAndClinic entity:

    public int Id { get; set; }
    public int HospitalId { get; set; }
    public int ClinicId { get; set; }
    [ForeignKey("HospitalId")]
    public Hospital Hospital { get; set; }
    [ForeignKey("ClinicId")]
    public Clinic Clinic { get; set; }

This is the Doctor entity:

    public string Branch { get; set; }
    public int? HospitalAndClinicId { get; set; }
    [ForeignKey("HospitalAndClinicId")]
    public HospitalAndClinic HospitalAndClinic { get; set; }

This is my employee entity

    public string Position { get; set; }
    public int HospitalAndClinicId { get; set; }
    [ForeignKey("HospitalAndClinicId")]
    public HospitalAndClinic HospitalAndClinic { get; set; }

My Doctorand 'Employee' tables extend from Person class that has fields like id, name etc.

When I do migration I get this problem

Introducing FOREIGN KEY constraint 'FK_Doctor_HospitalAndClinic_HospitalAndClinicId' on table 'Doctor' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

How can I solve this?

1 Answers

In the migration, under constrains you can add onDelete property to say what happens when deleted.

        migrationBuilder.CreateTable(
            name: "Doctor",
            columns: table => new
            {
                Id = table.Column<int>(nullable: false),
                .
                .
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_Doctor", x => x.Id);
                table.ForeignKey(
                    name: "FK_Doctor_HospitalAndClinic_HospitalAndClinicId",
                    column: x => x.HospitalAndClinicId,
                    principalTable: "HospitalAndClinic",
                    principalColumn: "Id",
                    onDelete: ReferentialAction.NoAction);  // <---- Add this.
            });

Or what you can also do is, as Hopeless pointed out, use fluent API to configure your model by overriding the OnModelCreating method in your derived context.

modelBuilder.Entity<Doctor>()
    .HasOne(e => e.HospitalAndClinic)
    .WithMany()
    .OnDelete(DeleteBehavior.NoAction); // <-- Add this

Visit here to see all DeleteBehaviors and visit here to see all ReferentialActions

Related