代码优先 Entity Framework : 外键 - 无效的对象名称

Code-first Entity Framework : foreign key - invalid object name

我在使用 Entity Framework 和代码优先方法时遇到问题。

外键不会link正确

这是错误页面:(https://prnt.sc/JUWTdRVCEWq7)

public class Organisme
{
    public int ID { get; set; }
    public string Name { get; set; } = null! ;
    public string Description { get; set; } = null! ;
    public string Image { get; set; } = null! ;

    public Soort Soort { get; set; } = null!;
}

public class Soort
{
    public int Id { get; set; }
    public string Name { get; set; } = null!;
    public Geslacht Geslacht { get; set; } = null!;

    public ICollection<Organisme> Organismes { get; set; } = null!;
}


modelBuilder.Entity<Soort>().HasMany(a => a.Organismes).WithOne(b => b.Soort);


public async Task<Organisme?> GetByIdAsync(int id)
{
    using OrganismeContext oc = new();
    return await oc.Organismes.AsNoTracking()
                   .Include(x => x.Soort)
                   .SingleOrDefaultAsync(x => x.ID == id);
}

通过删除 .Include(x => x.Soort),我不再收到错误,但值变为 null,这不是我想要的

添加 .HasForeignKey(c => c.Soort) 会产生完全不同的错误

InvalidOperationException: 'Soort' cannot be used as a property on entity type 'Organisme' because it is configured as a navigation.

错误页面:https://prnt.sc/1GL3-CgD1ruj and https://prnt.sc/GymTfEIhXy5x

You have your navigation property (Soort) but no foreign key column, so EF doesn't know how to link the two up, hence why you get error when trying to include. Add both a Foreign Key Property and a Navigation Property to your entity model, so for example, class Organisme { [ForeignKey(nameof(Soort)] public int SoortId {get; set;} public Soort Soort {get; set;} }

来自@nbokmans 的评论