简体   繁体   English

实体框架6中关系的多样性从1对多变为1对0或0..1

[英]Multiplicity of relationship changes in Entity Framework 6 from 1-to-many to 1-to-0 or 0..1

I am working with two entities County and Patient which have a 1 to many relationship. 我正在与两个实体County和Patient建立一对一关系。

public class County
{
   public int CountyId { get; set; }  // Primary Key
   public string CountyName { get; set; ) // A unique index column
   public virtual ICollection<Patient> Patients { get; set; }
}

public class CountyMap : EntityTypeConfiguration<County>
{
    public CountyMap()
    {
        ToTable("Counties");
        HasKey(c => c.CountyId);
        Property(c => c.CountyId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            Property(c => c.CountyName).IsRequired().HasMaxLength(50).HasColumnAnnotation("Index",
                new IndexAnnotation(new IndexAttribute("IX_Counties", 1) { IsUnique = true }));
    }
}

public class Patient
{
    public int PatientId { get; set; }
    public string PatientLastName { get; set; }
    public string PatientFirstName { get; set; }
    public string CountyName { get; set; }
    public int CountyId { get; set; } // Foreign key to Counties table
    public virtual County County { get; set; } // Navigation property
}

public class PatientMap: EntityTypeConfiguration<Patient>
{
    public PatientMap()
    {
            ToTable("Patients");
            HasKey(p => p.PatientId);
            Property(p => p.PatientId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            Property(p => p.PatientLastName).IsRequired().HasMaxLength(50);
            Property(p => p.PatientFirstName).IsRequired().HasMaxLength(50);
            Property(p => p.CountyId).IsRequired();
            HasRequired(p => p.County).WithMany(c => c.Patients).HasForeignKey(p => p.CountyId);
    }
}

public class AppContext : DbContext
{
    public AppContext()
        : base("name=AppContext")
    {
    }

    public virtual DbSet<County> Counties { get; set; }
    public virtual DbSet<Patient> Patients { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new CountyMap());
        modelBuilder.Configurations.Add(new PatientMap());
    }
}

public class PatientUOW
{
    public Patient CreatePatient(Patient patient)
    {
        string errorMessage = String.Empty;
        Patient patientReturned = null;
        County county = null;

        try
        {
           using (AppContext ctx = new AppContext())
           {
               // ONLY Pre-existing counties are permitted
                county = ctx.Counties.Where(c => c.CountyName == patient.CountyName).SingleOrDefault<County>();

                county.Patients.Add(patient);
                ctx.SaveChanges();  // An exception is thrown here

           }
        }
        catch (Exception err)
        {
        }
    }
}

The exception message is: 异常消息是:

Multiplicity constraint violated. 违反多重性约束。 The role 'Patient_County_Target' of the relationship 'ArielOperations.Domain.Concrete.Patient_County' has multiplicity 1 or 0..1. 关系“ ArielOperations.Domain.Concrete.Patient_County”的角色“ Patient_County_Target”的多重性为1或0.1。

The debugger on the County entity shows: County实体上的调试器显示:

在此处输入图片说明

and 在此处输入图片说明

Can anyone explain what is happening here? 谁能解释这里发生了什么? I've seen several entries here and elsewhere and none seem to work. 我在这里和其他地方都看到了几条条目,但似乎都没有。

Thank you. 谢谢。

I was able to resolve my issue. 我能够解决我的问题。 The key seems to be to avoid attempting to create a new County record when adding a Patient in a County. 关键似乎是要避免在县中添加患者时尝试创建新的县记录。 To achieve this I did not pass a County instance to the CreatePatient method. 为此,我没有将County实例传递给CreatePatient方法。 The new Patient only contains the CountyId of the target County. 新的患者仅包含目标县的县编号。

Patient newPatient = new Patient
{
    PatientLastName = "Doe",
    PatientFirstName = "Jane",
    CountyName = "Denton",
    CountyId = 4
};

We can now pass this newPatient instance to the CreatePatient method. 现在,我们可以将此newPatient实例传递给CreatePatient方法。

public Patient CreatePatient(Patient patient)
{
    string errorMessage = String.Empty;
    Patient patientReturned = null;
    County county = null;

    try
    {
            using (AppContext ctx = new AppContext())
           {
               // ONLY Pre-existing counties are permitted
                county = ctx.Counties.Where(c => c.CountyName == patient.CountyName).SingleOrDefault<County>();
                ctx.Patients.Add(patient);
                ctx.SaveChanges();
                patientReturned = patient;
           }
    } // end try
    catch (Exception err)
    {
        errorMessage = err.Message;
    } // end catch (Exception err)

    return patientReturned;
} // end public Patient CreatePatient(Patient patient)

This seems to work and even connect the Patient to the County record via the foreign key. 这似乎可行,甚至可以通过外键将患者连接到县记录。 It seems EF does some things here to achieve the desired end. 似乎EF在这里做了一些事情以达到期望的目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM