Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplicity conflicts with the referential constraint Error

I get the following error when I run my application:

One or more validation errors were detected during model generation:

GuideMedApp.Models.NetworkPrescriber_Patients: : Multiplicity conflicts with the referential constraint in Role 'NetworkPrescriber_Patients_Source' in relationship 'NetworkPrescriber_Patients'. Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'.

I'm trying to create a relationship between entities 'NetworkPrescriber' and 'Patient'. The Patient entity has 2 foreign keys pointing to the NetworkPrescriber table.

Here's how the Models are defined:

Patient

[Table("Patient")]
public partial class Patient
{
    public long PatientID { get; set; }

    public long? NetworkPrescriberID { get; set; }

    public long? SecondaryNetworkPrescriberID { get; set; }

    public virtual NetworkPrescriber NetworkPrescriber { get; set; }

    public virtual NetworkPrescriber NetworkPrescriber1 { get; set; }

}

NetworkPrescriber

[Table("NetworkPrescriber")]
public partial class NetworkPrescriber
{
    public NetworkPrescriber()
    {
        Patients = new HashSet<Patient>();
        Patients1 = new HashSet<Patient>();

    }

    public long NetworkPrescriberID { get; set; }

    public virtual ICollection<Patient> Patients { get; set; }

    public virtual ICollection<Patient> Patients1 { get; set; }

}

The model configuration is as below:

    modelBuilder.Entity<NetworkPrescriber>()
                .HasMany(e => e.Patients)
                .WithOptional(e => e.NetworkPrescriber)
                .HasForeignKey(e => e.NetworkPrescriberID);

    modelBuilder.Entity<NetworkPrescriber>()
                .HasMany(e => e.Patients1)
                .WithOptional(e => e.NetworkPrescriber1)
                .HasForeignKey(e => e.SecondaryNetworkPrescriberID);

The error is suggesting there's a mismatch between how the model are defined and how they're configured withfluent API but I don't see any. How to I fix this error?

like image 628
Ahmed Mujtaba Avatar asked Feb 27 '26 18:02

Ahmed Mujtaba


1 Answers

Try to add this configuration:

modelBuilder.Entity<Patient>()
   .Property(p => p.NetworkPrescriberID).IsOptional();
modelBuilder.Entity<Patient>()
  .Property(p => p.SecondaryNetworkPrescriberID).IsOptional();
like image 53
Roman Marusyk Avatar answered Mar 01 '26 08:03

Roman Marusyk