EF Core LINQ 通过接口访问导航属性失败

大致描述一下,实体City继承BaseLocationILocation

点击查看示例
public interface ILocation
{
    public string GetName();
    public double GetX();
    public double GetY();
    public Point GetPoint();
}

public class BaseLocation
{
    [ForeignKey("Point")] public int PointRefId { get; set; }
    public virtual Point Point { get; set; }
}

[Table("point")]
public class Point
{
    [Key] public int Id { get; set; }
    public double X { get; set; }
    public double Y { get; set; }
}

[Table("city")]
public class City : BaseLocation, ILocation
{
    [Key] public int Id { get; set; }
    public string Name { get; set; }

    public double GetX()
    {
        return Point.X;
    }

    public double GetY()
    {
        return Point.Y;
    }

    public Point GetPoint()
    {
        return Point;
    }

    public string GetName()
    {
        return Name;
    }
}

通过ILocation访问数据时:

var result = await db.Cities
    .Select(
        s => new
        {
            Point1 = s.GetPoint(),  // 不能用
            Point2 = s.Point,
        }
    ).ToListAsync();

通过继承属性可访问,通过接口不能访问,报错"command is already in progress".

https://www.v2ex.com/t/841550#reply4

原因应是导航属性并没有被懒加载,尽管我已经用了Lazy Loading (因为通过继承属性也可以访问)

使用Eagerly Loading可以解决这个问题,即在Select之前使用Include语句。

var result = await db.Cities
    .Include(c => c.Point)
    .Select(
        s => new
        {
            Point = s.GetPoint(), 
        }
    ).ToListAsync();

分析来看,使用继承属性成功懒加载,但通过接口访问导航属性时未能正常完成懒加载,手动Include之后工作正常。

具体原因等再查文档后补充。

posted @ 2022-03-20 20:38  陈昱行  阅读(100)  评论(0编辑  收藏  举报