简体   繁体   English

代码优先实体框架:外键 - 无效的对象名称

[英]Code-first Entity Framework : foreign key - invalid object name

I'm having trouble with Entity Framework and the code-first approach.我在使用实体框架和代码优先方法时遇到问题。

Foreign key will not link properly外键无法正确链接

Here is the error page: ( https://prnt.sc/JUWTdRVCEWq7 )这是错误页面:( 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);
}

By removing .Include(x => x.Soort) , I no longer get the error, but the value becomes null which is not what I want通过删除.Include(x => x.Soort) ,我不再收到错误,但值变为null这不是我想要的

Adding .HasForeignKey(c => c.Soort) gives a whole different error添加.HasForeignKey(c => c.Soort)会产生完全不同的错误

InvalidOperationException: 'Soort' cannot be used as a property on entity type 'Organisme' because it is configured as a navigation. InvalidOperationException:“Soort”不能用作实体类型“Organisme”的属性,因为它被配置为导航。

Error pages: https://prnt.sc/1GL3-CgD1ruj and https://prnt.sc/GymTfEIhXy5x错误页面: https ://prnt.sc/1GL3-CgD1ruj 和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.您有导航属性 ( Soort ) 但没有外键列,因此 EF 不知道如何将两者链接起来,因此为什么在尝试包含时会出错。 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;} }将外键属性和导航属性都添加到实体模型中,例如, class Organisme { [ForeignKey(nameof(Soort)] public int SoortId {get; set;} public Soort Soort {get; set;} }

from @nbokmans in comments来自@nbokmans 的评论

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM