[英]Correct annotation to set primary key in Entity Framework code-first
將事件添加到dbContext
,可以看到EF創建的表沒有我認為的主鍵。 我以為實體框架將使用名為[class name]Id
的成員作為主鍵。 在Event
類中,它將是EventId
。 但是此列中的所有條目都接收到ID 0。
實體框架是這樣工作的,因為我期望每個EventId
都是唯一的並設置為主鍵。 而是將LocationId
設置為主鍵和外鍵。 該類具有LocationId
批注Key
和Foreign Key
。 這是因為我正在關注的教程。 對我來說,用外鍵注釋Location並用Key
注釋EventId
有意義的。
這是我的Event
課:
public class Event
{
public Event()
{
_sessions = new List<Session>();
}
public int EventId { get; set; }
public string Name { get; set; }
public DateTime Date { get; set; }
[Key, ForeignKey("Location") ]
public int LocationId { get; set; }
public virtual Location Location { get; set; }
ICollection<Session> _sessions;
public virtual ICollection<Session> Sessions {
get { return _sessions; }
set { _sessions = value; }
}
}
從LocationId刪除密鑰並執行此操作
[ForeignKey("Location")]
public int LocationId { get; set; }
並像這樣在EventId上添加[Key]
[Key]
public int EventId { get; set; }
有關更多詳細信息,請參見此鏈接
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.