我首先使用實體框架4,mvc4和代碼。選項1:1映射,主要實體不包含FK
我與創建一個選項1掙扎:1名映射,其中具有可選1的主要實體:1映射沒有FK它:
public class User
{
[Column("user_id")]
public int Id {get;set;}
public virtual House House {get;set;} // optional mapping
}
public class House
{
[Column("house_id")]
public int Id {get;set;}
[Column("user_id")]
public int UserId {get;set;}
}
通知用戶如何表沒有teI houseId列。
我該如何正確映射?
注意:下面的方法並不是我真正想要做的,因爲它迫使我在House模型上添加一個導航屬性,並返回給User。
這個方法我試過,但我不得不虛擬屬性添加到我不想做房屋模型:How do I code an optional one-to-one relationship in EF 4.1 code first with lazy loading and the same primary key on both tables?
所以我的配置看起來像上面的嘗試:
public class UserConfiguration : EntityTypeConfiguration<User>
{
public UserConfiguration()
{
this.ToTable("User", SchemaName);
this.HasKey(x => x.Id);
this.HasOptional(x => x.House);
}
}
public class HouseConfiguration : EntityTypeConfiguration<House>
{
public HouseConfiguration()
{
this.ToTable("House", SchemaName);
this.HasKey(x => x.Id);
this.HasRequired(vc => vc.User).WithRequiredDependent(v => v.House);
}
}
但是當我這樣做,保存模型我得到這個錯誤:
Cannot insert explicit value for identity column in table 'House' when IDENTITY_INSERT is set to OFF
注:若沒有上述設置(映射和配置uration),House實體可以很好地保存到數據庫,並且身份正確設置。
現在我得到:ReferentialConstraint中的依賴屬性映射到商店生成的列。專欄:'House_Id'。 – loyalflow
1:1關係需要依賴關係具有相同的主鍵。 DatabaseGeneratedOption.None在相關主鍵上。一旦你告訴EF你有1:1的關係,它期待着相同的密鑰。即使DB首先不是必需的。但是你真的有1:1的關係嗎? –
@soadyp是可選的1:1,這意味着用戶帳戶可以有0或1個House記錄。 – loyalflow