[英]Entity Framework : Object is null but the foreign key isn't
我正在學習.NET Core和EF Core,但是我已經遇到了問題。
我是從頭開始創建代碼的,
這是我的代碼:
public class DBContext : DbContext
{
public DbSet<Muscle> Muscle { get; set; }
public DbSet<Exercice> Exercice { get; set; }
}
public class Muscle
{
[Key]
public int id { get; set; }
public string nom { get; set; }
public virtual ICollection<Exercice> Exercices { get; set; }
}
public class Exercice
{
[Key]
public int id { get; set; }
public string libelle { get; set; }
public int MuscleId { get; set; }
public virtual Muscle Muscle { get; set; }
}
當我嘗試獲取我的第一個“鍛煉”時,他的“ MuscleId”為“ 1”,但他的“肌肉”為空...並且如果我嘗試獲取我的第一個“ Muscle”,則“鍛煉”也為空...
我需要做些什么才能使這項工作嗎? 謝謝
您的肌肉類主鍵應與運動類上的外鍵匹配。 像這樣。
public class Muscle
{
[Key]
public int MuscleId { get; set; }
public string nom { get; set; }
public virtual ICollection<Exercice> Exercices { get; set; }
}
或使用[ForeignKey]屬性。 你可以在這里閱讀更多。 http://www.entityframeworktutorial.net/code-first/foreignkey-dataannotations-attribute-in-code-first.aspx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.