Home > Net >  Code-first Entity Framework : foreign key - invalid object name
Code-first Entity Framework : foreign key - invalid object name

Time:06-03

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)

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

Adding .HasForeignKey(c => c.Soort) gives a whole different error

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

Error pages: https://prnt.sc/1GL3-CgD1ruj and https://prnt.sc/GymTfEIhXy5x

CodePudding user response:

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;} }

from @nbokmans in comments

  • Related