0
我正在與具有1對多關係的兩個實體County和Patient一起工作。實體框架6中的多重關係變化從1對多到1對0或0..1
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。
在縣實體的調試器顯示:
誰能解釋這裏發生了什麼?我在這裏和其他地方看到了幾個條目,而且沒有一條似乎有效。
謝謝。
爲什麼'Patient'有'CountyName'?這是多餘的。 –