【问题标题】:Entity Framework : Object is null but the foreign key isn't实体框架:对象为空,但外键不是
【发布时间】:2019-03-12 09:22:51
【问题描述】:

我正在学习 .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”为空... 如果我尝试获得我的第一个“肌肉”,“锻炼”也是无效的......

我需要做些什么来完成这项工作吗? 谢谢

【问题讨论】:

  • 从 DbContext 查询时尝试使用Include()。这是我的一个项目中的一个示例:DifferencesContext db = new DifferencesContext(); var differences = db.Differences.Include(d =&gt; d.Branch).Include(d =&gt; d.DifferenceType).Include(d =&gt; d.State).ToList()。如果没有Include(),这三个属性始终为空(Branch、DifferenceType、State),仅返回键(BranchId、.. 等)。我认为这与 EntityFramework 和 EntityFrameworkCore 相同

标签: c# model .net-core foreign-keys ef-core-2.1


【解决方案1】:

你的肌肉类主键应该与运动类的外键匹配。像这样。

public class Muscle
{
    [Key]
    public int MuscleId { get; set; }
    public string nom { get; set; }
    public virtual ICollection<Exercice> Exercices { get; set; }
}

或者使用 [外键] 属性。 你可以在这里阅读更多。 http://www.entityframeworktutorial.net/code-first/foreignkey-dataannotations-attribute-in-code-first.aspx

【讨论】:

  • 我尝试使用 [ForeignKey] 但没有更改...:/ 并且使用“同名”不会改变任何事情,因为我的“MuscleId”不为空。只有“肌肉”是
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-14
  • 2013-08-14
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
相关资源
最近更新 更多