Been stuck for hours with this weird problem. For some reason entity framework wont load the navigation properties of this 1 to many relationship, even though the generated SQL seems to be right, foreign key exists from SubItems to FrontPageItems:
CONSTRAINT [FK_dbo.SubItems_dbo.FrontPageItems_FrontPageItemId]
FOREIGN KEY ([FrontPageItemId])
REFERENCES [dbo].[FrontPageItems] ([Id]) ON DELETE CASCADE
I have tried loading all frontpageitems with:
_repo.Get();, but even though the SubItem table contains foreign keys referencing to FronPageItems table, no navigation properties gets loaded.
public class FrontPageItem : Logger, IEntity, IIsPublished
{
public FrontPageItem()
{
SubItems = new HashSet<SubItem>();
}
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool IsPublished { get; set; }
public virtual ICollection<SubItem> SubItems { get; set; }
}
public class SubItem : Logger, IEntity, IIsPublished
{
public SubItem()
{
FrontPageItem = new FrontPageItem();
}
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string YoutubeUrl { get; set; }
public virtual FrontPageItem FrontPageItem { get; set; }
public int FrontPageItemId { get; set; }
public bool IsPublished { get; set; }
}
public class SampleContext : IdentityDbContext<ApplicationUser>
{
// throwIfV1Schema is used when upgrading Identity in a database from 1 to 2.
// It's a one time thing and can be safely removed.
public SampleContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static SampleContext Create()
{
return new SampleContext();
}
// Define you conceptual model here. Entity Framework will include these types and all their references.
public IDbSet<FrontPageItem> FrontPageItem { get; set; }
public IDbSet<SubItem> SubItems { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// The DateTime type in .NET has the same range and precision as datetime2 in SQL Server.
// Configure DateTime type to use SQL server datetime2 instead.
modelBuilder.Properties<DateTime>().Configure(c => c.HasColumnType("datetime2"));
base.OnModelCreating(modelBuilder);
}
}
Btw it works if I remove the foreignkey property in SubItem:
public int FrontPageItemId { get; set; }
I have tried eager loading with include like this:
var frontPageItems = _repo.AsQueryable().Include(o => o.SubItems).ToList();
_repo.Get()? Why do you expect it to load related entities for you automatically? Do you have lazy loading enabled?