【问题标题】:Multiplicity of relationship changes in Entity Framework 6 from 1-to-many to 1-to-0 or 0..1Entity Framework 6 中关系的多样性从 1 对多变为 1 对 0 或 0..1
【发布时间】:2017-10-05 19:03:31
【问题描述】:

我正在与具有一对多关系的两个实体 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)
        {
        }
    }
}

异常信息是:

违反了多重性约束。的角色“Patient_County_Target” 'ArielOperations.Domain.Concrete.Patient_County' 的关系有 多重性 1 或 0..1。

County 实体上的调试器显示:

谁能解释这里发生了什么?我在这里和其他地方看到了几个条目,但似乎没有一个有效。

谢谢。

【问题讨论】:

  • 为什么PatientCountyName?这是多余的。

标签: c# entity-framework code-first


【解决方案1】:

我能够解决我的问题。关键似乎是避免在县中添加患者时尝试创建新的县记录。为此,我没有将 County 实例传递给 CreatePatient 方法。新 Patient 仅包含目标县的 CountyId。

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

我们现在可以将这个 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)

这似乎有效,甚至可以通过外键将患者连接到县记录。看来 EF 在这里做了一些事情来达到预期的目的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-22
    • 1970-01-01
    • 2013-10-28
    • 1970-01-01
    • 2012-09-22
    • 1970-01-01
    相关资源
    最近更新 更多