Entity Framework Foreign Key restraint
Hi all, I'm trying to make an appointment scheduling system.
The appointment section has its own database linked to a patients model and an appointment model.
The error happens when I try save a new appointment -
These are my models:
The appointment section has its own database linked to a patients model and an appointment model.
The error happens when I try save a new appointment -
_appointmentContext.SaveChanges();_appointmentContext.SaveChanges();These are my models:
public class AppointmentDbContext : DbContext
{
public DbSet<Appointment> Appointments { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// Set the file location for the patient database
optionsBuilder.UseSqlite("Data Source=appointment.db");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Appointment>()
.HasOne(a => a.Patient)
.WithMany(p => p.Appointments) // Matches Patient.Appointments
.HasForeignKey(a => a.PatientId)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<Appointment>()
.HasOne(a => a.User)
.WithMany()
.HasForeignKey(a => a.UserId)
.OnDelete(DeleteBehavior.Restrict);
}
public enum AppointmentStatus
{
Completed = 1,
Scheduled = 2,
Cancelled = 3,
} //UserAccountType
public class Appointment
{
public int Id { get; set; }
public DateTime Scheduled { get; set; }
public AppointmentStatus Status { get; set; }
//navigation properties
public int PatientId { get; set; }
public Patient Patient { get; set; }
public int UserId { get; set; }
public User User { get; set; }
}
}
} public class AppointmentDbContext : DbContext
{
public DbSet<Appointment> Appointments { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// Set the file location for the patient database
optionsBuilder.UseSqlite("Data Source=appointment.db");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Appointment>()
.HasOne(a => a.Patient)
.WithMany(p => p.Appointments) // Matches Patient.Appointments
.HasForeignKey(a => a.PatientId)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<Appointment>()
.HasOne(a => a.User)
.WithMany()
.HasForeignKey(a => a.UserId)
.OnDelete(DeleteBehavior.Restrict);
}
public enum AppointmentStatus
{
Completed = 1,
Scheduled = 2,
Cancelled = 3,
} //UserAccountType
public class Appointment
{
public int Id { get; set; }
public DateTime Scheduled { get; set; }
public AppointmentStatus Status { get; set; }
//navigation properties
public int PatientId { get; set; }
public Patient Patient { get; set; }
public int UserId { get; set; }
public User User { get; set; }
}
}
}