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 @   陈昱行  阅读(112)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示