我可以在 Entity Framework 6 中使用没有强元素类型的 DbContext.Database.SqlQuery 吗?

Can I use DbContext.Database.SqlQuery without a strong element type in Entity Framework 6?

我正在实施一些从数据库中查询 ID 的通用解决方案。我所知道的是,例如给定一个 table A,它有一个整数类型的列 Id。不知道是uint32还是int64

我想使用 DbContext.Database.SqlQuery 查询 ID 的最大值,但是,我无法使其以弱类型方式工作。所以我总是必须提供一个强元素类型,基本上我不喜欢它可能是 intlong.

如果我 运行 就像 .SqlQuery<object>,那么我在尝试使用 Convert.ToInt64 将其转换为例如 long 时遇到异常,说System.Object 不能转换为该类型。好像 EF 对我有点误解。

即使实际的基础类型是 Int32,并且我尝试查询 long,我也会收到一个异常,指出我无法将 Int32 转换为 long ,这对我来说完全没有意义。

我怎样才能获得一个弱类型的查询结果,我可以将其转换为我想要的任何内容?

不幸的是,Entity Framework 被设计为映射 definite (strong typed) POCO classes

The names of the types and each of the mapped properties must be equivalent.

  • 例如,您可以使用 those techniqueslong 转换为 int。但这也需要您事先了解列类型。
  • 您可以使用 codes shown here. But that is overkill compared with ADO.NET,IMO 转换为 dynamic 类型。