使用此:
public class User
{
public string ID { get; set; }
public string LastName { get; set; }
public string Password { get; set; }
public string FirstName { get; set; }
public Profile Profile { get; set; }
}
public class Profile
{
[Key, ForeignKey("User")]
public int ProfileID { get; set; }
public string ProfileName { get; set; }
public DateTime CreateDate { get; set; }
public DateTime LastUpdateDate { get; set; }
public User User { get; set; }
}
這是建立在EF一個一對一的關係,唯一有效的方式 - 依靠實體的PK也必須FK到主要實體。在EF中沒有像雙向一對一的關係,因爲它不能在EF中工作。
人們如何克服這種情況的方式是兩個一對多的關係,其中principal沒有依賴實體的導航集合+在數據庫中手動定義唯一鍵。需要手動映射:
public class User
{
public string ID { get; set; }
public string LastName { get; set; }
public string Password { get; set; }
public string FirstName { get; set; }
// one side MUST be nullable otherwise you have bidirectional constraint where each
// entity demands other side to be inserted first = not possible
public int? ProfileId { get; set; }
public Profile Profile { get; set; }
}
public class Profile
{
public int ProfileID { get; set; }
public string ProfileName { get; set; }
public DateTime CreateDate { get; set; }
public DateTime LastUpdateDate { get; set; }
public int UserId { get; set; }
public User User { get; set; }
}
而在映射將定義:
modelBuilder.Entity<User>
.HasOptional(u => u.Profile)
.WithMany()
.HasForeignKey(u => u.ProfileId);
modelBuilder.Entity<Profile>
.HasRequired(u => u.User)
.WithMany()
.HasForeignKey(u => u.UserId);
現在您必須在數據庫中定義唯一的鑰匙 - 如果你正在使用的代碼先使用custom database initialize河請注意,仍然雙向一對一是錯誤的概念,因爲雙方都要求唯一的FK,其中NULL仍然包含在唯一值中,因此一旦在Profile
之前插入User
,則不得有任何其他User
而沒有Profile
。這可能會導致可序列化的事務。
你得到的錯誤是什麼? – Eranga 2011-06-08 08:50:43