I’m trying to make a one-to-one relationship as it’s shown on the learn microsoft website, but when I try to get it from the repository using a include it gives me this error, and I can’t figure out why as I don’t have problems with other types of include, only when it’s one to one it generates an error…
The expression ‘p.BlogHeader’ is invalid inside an ‘Include’ operation, since it does not represent a property access: ‘t => t.MyProperty’. To target navigations declared on derived types, use casting (‘t => ((Derived)t).MyProperty’) or the ‘as’ operator (‘t => (t as Derived).MyProperty’). Collection navigation access can be filtered by composing Where, OrderBy(Descending), ThenBy(Descending), Skip or Take operations. For more information on including related data, see http://go.microsoft.com/fwlink/?LinkID=746393.
That’s the classes and the model configuration
// Principal (parent)
public class Blog
{
public int Id { get; set; }
public BlogHeader? Header { get; set; } // Reference navigation to dependent
}
// Dependent (child)
public class BlogHeader
{
public int Id { get; set; }
public int BlogId { get; set; } // Required foreign key property
public Blog Blog { get; set; } = null!; // Required reference navigation to principal
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.HasOne(e => e.Header)
.WithOne(e => e.Blog)
.HasForeignKey<BlogHeader>(e => e.BlogId);
}
This is the include operation I’m trying to do
public override Task<Blog?> GetByIdAsync(long blogId)
{
return DbSet
.Include(p => p.BlogHeader)
.SingleOrDefaultAsync(p => p.Id == blogId);
}