基於拉吉斯拉夫出色的答案,這裏是如何做到這一點,而無需使用任何映射 - 只是屬性應用到模型類本身:
public class Group
{
public int Id { get; set; }
[MaxLength(300)]
public string Name { get; set; }
public ICollection<User> Users { get; set; }
}
public class User
{
public int Id { get; set; }
[MaxLength(300)]
public string Name { get; set; }
[ForeignKey("PrimaryGroup")]
public int PrimaryGroupId { get; set; }
[Required]
public Group PrimaryGroup { get; set; }
[InverseProperty("Users")]
public ICollection<Group> SecondaryGroups { get; set; }
}
注意事項
如果需要,可以將虛擬關鍵字添加到2 ICollection
和Group
。這allows lazy-loading。在性能方面,我不推薦它,但它是可能的。
我包含的MaxLength
屬性的任意(但安全)長度爲300
,因爲在沒有MaxLength的情況下將字符串放在EF中可以獲得低性能的NVarChar(MAX)
列。完全不相關的問題,但更好地發佈好的代碼。
我建議您的EF類的類名稱爲「User」和「Group」。他們會讓你以後嘗試運行的任何SQL複雜化,必須鍵入[User]和[Group]才能訪問它們,並且在類別User
將與Context
屬性User
衝突的MVC控制器中使用這些類會變得複雜訪問Asp.Net Identity庫。
我可以說拉迪斯拉夫,這是我曾經有幸遇到過/用來解決我確切問題的最有用的帖子之一!謝謝! – LiverpoolsNumber9 2011-11-03 16:48:09
Lad是實體框架的人,非常感謝擁有如此豐富的資源。還有一個原因是這個棧太棒了! – Sam 2012-08-12 17:46:33