Skip to content

Casting using an Explicit Static Operator breaks Include Statements #30599

@Pieeer1

Description

@Pieeer1

This is pretty easily reproduceable, but frustrating in the same:
Relationship Example:

public class Forum
{
    private Forum() { }
    public Forum(double differentId) { DifferentId = differentId; }
    public Forum(Blog blog) { DifferentId = (double)blog.Id; Posts = blog.Posts; }
    public double DifferentId { get; set; }
    public ICollection<Post> Posts { get; set; } = null!;
}
public class Blog
{
    private Blog() { }
    public Blog(int id) { Id = id; }
    public int Id { get; set; }
    public static explicit operator Forum(Blog blog) { return new Forum(blog); }
    public ICollection<Post> Posts { get; set; } = null!;
}
public class Post
{ 
    public int Id { get; set; }
    public virtual Blog Blog { get; set; } = null!;
    public int BlogId { get; set; }
}

Bug Example:

        _blogRepository.GetAll().Include(x => x.Posts).ToList(); // returns the posts
        _blogRepository.GetAll().Include(x => x.Posts).Select(x => new Forum(x)); // returns the posts
        _blogRepository.GetAll().Include(x => x.Posts).Cast<Forum>(); // does not return the posts

There are no exceptions thrown in this case

EF Core version: 7.0.4
Database provider: (e.g. Microsoft.EntityFrameworkCore.SqlServer)
Target framework: (e.g. .NET 7.0)
Operating system: Windows 10
IDE: (e.g. Visual Studio 2022 17.4)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions