EF Core LINQ 通过接口访问导航属性失败
大致描述一下,实体City
继承BaseLocation
, ILocation
:
点击查看示例
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".
原因应是导航属性并没有被懒加载,尽管我已经用了Lazy Loading (因为通过继承属性也可以访问)
使用Eagerly Loading可以解决这个问题,即在Select之前使用Include语句。
var result = await db.Cities .Include(c => c.Point) .Select( s => new { Point = s.GetPoint(), } ).ToListAsync();
分析来看,使用继承属性成功懒加载,但通过接口访问导航属性时未能正常完成懒加载,手动Include之后工作正常。
具体原因等再查文档后补充。
站外博客地址:https://blog.yuhang.ch
分类:
.Net Core
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南