Foreign key "The property X on entity type Y could not be found" Entity Framework Core

c# entity-framework entity-framework-core foreign-keys

Question

I've just started working with EF. I have simple models Page and Related Pages.

public class Page
{
    public int ID { get; set; }
    [Required]
    public string UrlName { get; set; }
    [Required]
    public string Title { get; set; }
    public List<RelatedPages> RelPages1 { get; set; }
    public List<RelatedPages> RelPages2 { get; set; }
}
public class RelatedPages
{
    public int ID { get; set; }
    public int Page1ID { get; set; }
    public Page Page1 { get; set; }
    public int Page2ID { get; set; }
    public Page Page2 { get; set; }
}

This is in my DbContext:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Page>().HasIndex(x => x.UrlName).IsUnique();

    modelBuilder.Entity<RelatedPages>().HasOne(x => x.Page1).WithMany(x => x.RelPages1).HasForeignKey(x => x.Page1ID);
    modelBuilder.Entity<RelatedPages>().HasOne(x => x.Page2).WithMany(x => x.RelPages2).HasForeignKey(x => x.Page2ID);
}

Though when I try to execute command

dbContext.Pages.Where(x => x.RelPages1 != null);

I have an exception

InvalidOperationException: The property 'Page1ID' on entity type 'Page' could not be found. Ensure that the property exists and has been included in the model.

1
1
8/8/2016 7:04:13 PM

Popular Answer

This is appears to be a bug in EF Core. You can file issues at https://github.com/aspnet/EntityFramework/issues.

If what you are trying to query for is the set of all pages that have at least one RelPages1, then a LINQ query that doesn't have the same bug and returns the expect result is:

dbContext.Pages.Where(x => x.RelPages1.Count() > 0)
2
8/9/2016 2:56:56 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow