首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >实体框架6中关系从1到多到1到0或0.1的多重关系变化

实体框架6中关系从1到多到1到0或0.1的多重关系变化
EN

Stack Overflow用户
提问于 2017-05-07 20:37:08
回答 1查看 150关注 0票数 0

我与两个实体县和病人有一个1到多的关系。

代码语言:javascript
复制
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)
        {
        }
    }
}

例外消息是:

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

县实体上的调试器显示:

有人能解释一下这里发生了什么吗?我在这里和其他地方见过几个条目,但似乎都没有用。

谢谢。

EN

回答 1

Stack Overflow用户

发布于 2017-05-24 21:46:10

我解决了我的问题。关键似乎是避免试图创建一个新的县记录时,增加一个病人在县。为了实现这一点,我没有将县实例传递给CreatePatient方法。新病人只包含目标县的CountyId。

代码语言:javascript
复制
Patient newPatient = new Patient
{
    PatientLastName = "Doe",
    PatientFirstName = "Jane",
    CountyName = "Denton",
    CountyId = 4
};

现在我们可以将这个newPatient实例传递给CreatePatient方法。

代码语言:javascript
复制
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在这里做了一些事情来达到预期的目的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43836432

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档