'Entity Framework Code First OneToMany collection from foreign key

We are in the middle of a modernization effort and are trying to temporarily map something in entity framework which is giving us a ton of problems. We are not using EF Core. We are on .NET Framework 4.8.

We are introducing a new Item at the root of all of our tables. Please note this example is contrived we are not actually building the data model seen below i've done my best to make it generic yet understandable.

Vehicle has a required item (fk = ItemID) An Item Has Many ItemGroups (fk ItemID)

public class Vehicle{
   [Key]
   public int VehicleID {get;set;}

   public long ItemID {get;set;}
   public virtual Item Item {get;set; }
   public virtual ICollection<ItemGroup> ItemGroups {get;set;} 
}

public class Group{
   [Key]
   public long GroupID {get;set;}

   /* note we have other properties on this table */ 

}

public class Item{
   [Key]
   public long ItemID {get;set;}
   /* note we have other properties on this table */ 

   public virtual ICollection<ItemGroup> ItemGroups {get;set;} 
}

/*
   I think the issue is here our PK for this table is ItemGroupID not ItemID or GroupID.
*/
public class ItemGroup{
   [Key]
   public long ItemGroupID {get;set;}

   public long ItemID {get;set;}
   public long GroupID {get;set;}

   /* note we have other properties on this table */ 

   public virtual Item Item {get;set; }
   public virtual Group Group {get;set; }

   public virtual ICollection<ItemGroup> ItemGroups {get;set;} 
}




public class OurDbContext{
   private void OnCreate(DbModelBuilder modelBuilder){
        modelBuilder.Entity<Item>()
            .HasMany(o => o.ItemGroup)
            .WithRequired(o => o.Item)
            .HasForeignKey(oct => oct.ItemID);
   }

}

This code is producing an error in the Vehicle class

Invalid column name 'Vehicle_VehicleID'.

This happens when we try to filter/access vehicle.ItemGroup.

e.g.


   _context.Vehicles.Where(x=>x.ItemGroup.Any()).ToList();

The following works fine, but we would prefer to not join through the item table.

   _context.Vehicles.Where(x=>x.Item.ItemGroup.Any()).ToList();



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source