2012-10-05 111 views
0

我想要定義以下模型,其中約會表具有用於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)。

回答

1

實體框架不支持這一點。當兩個表使用相同的密鑰(PersonId == AppointmentId)時,HasOptional().WithOptionalDependent()都可以工作,但這不是您的情況。爲了確保一個人沒有多個約會,您需要確保PersonIdAppointment表中是唯一的,並且實體框架不支持唯一約束。

你可以做的(不改變你的數據庫)是映射這是一個一對多的關係,即一個人可以有多個約會,並創建一個輔助屬性返回一個約會:

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

請注意,Entity Framework不會理解Appointment屬性,因此您無法在查詢中使用它。

相關問題