【问题标题】:Navigation property in optional:optional where only one table has foreign key可选中的导航属性:可选,其中只有一个表具有外键
【发布时间】:2012-10-05 11:36:55
【问题描述】:

我正在尝试定义以下模型,其中 Appointment 表具有 Person 的外键,并且实体都具有彼此的导航属性。

public class Appointment
{
    public int AppointmentId { get; set; }

    // Foreign Key property (this will be created in DB)
    public int? PersonId { get; set; }

    // Navigation property to Flatmate
    public virtual Person Person { get; set; }
}

public class Person
{
    public int PersonId { get; set; }

    // Just navigation property. Don't want Person table to include foreign key (no need)
    public virtual Appointment Appointment { get; set; }
}

我尝试使用流利的配置:

     modelBuilder.Entity<Appointment>()
            .HasOptional(a => a.Person)
            .WithOptionalDependent(p=> p.Appointment);

但我得到一个例外,它缺少一列(Appointment_AppointmentId 或 Person_PersonId,取决于我使用的是 WithOptionalDependent 还是 WithOptionalPrincipal)。

【问题讨论】:

    标签: .net entity-framework entity-framework-5


    【解决方案1】:

    实体框架不支持这个。当两个表使用相同的键 (PersonId == AppointmentId) 时,HasOptional().WithOptionalDependent() 可以工作,但这不是你的情况。为了确保一个人没有多个约会,您需要确保PersonIdAppointment 表中是唯一的,并且实体框架不支持唯一约束。

    您可以做的(不更改数据库)将其映射为一对多关系,其中一个人可以有多个约会,并创建一个辅助属性来返回一个约会:

    public virtual ICollection<Appointments> Appointments { get; set; }
    [NotMapped]
    public Appointment Appointment {
        get {
            return Appointments.SingleOrDefault();
        }
    }
    

    请注意,Entity Framework 无法理解 Appointment 属性,因此您不能在查询中使用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多