2012-09-04 51 views
3

如果我有一個導航屬性(即:虛擬的),例如:
public virtual User Author { get; set; }添加「ID」的屬性那裏有導航性能(EF)

而且我想也有該用戶的ID,即:
public int AuthorId { get; set; }

我該如何告訴EF這個「AuthorId」必須與Author屬性相關?

我不喜歡這是自動的想法(EF神奇地推斷這一點)。
因爲一個人可能對同一個表的多個引用:

public virtual User Author { get; set; } 
public int AuthorId { get; set; } 
public virtual User Receiver { get; set; } 
public int ReceiverId { get; set; } 

回答

7

實體框架將假設的AuthorID是Author類的FK。有關詳細信息,請參閱this blog post

你也可以明確地告訴EF,通過使用數據註釋:

[ForeignKey("Author")] 
public int AuthorId {get;set;} 

或使用流利的映射:

modelBuilder.Entity<YourClass>().HasRequired(p => p.Author) 
       .WithMany() 
       .HasForeignKey(p => p.AuthorId); 
+0

請閱讀我添加了什麼(編輯)主線程 – sports

+0

更新了更多詳細信息 –

+0

In:ForeignKey(「X」),X是一個類標識符還是屬性標識符? – sports