我对SQLite数据库有Entity Framework 4模型。部分模型看起来像这样 LINQ to Entities物化错误
所有Id字段的类型都是Guid(SQLite表DDL中的uniqueidentifier)。但是当我运行下面的LINQ查询时,我得到异常。
var query = AbonentPfrs.Select(a =>
new
{
AbPfr = a,
Pfr = a.PfrCertificates.Select(c => c.Id),
Ac = a.AcCertificates.Select(c => c.Id)
}
);
query.ToList();
当我运行它,我得到
System.InvalidOperationException: The type of the key field 'Id' is expected to be 'System.Guid', but the value provided is actually of type 'System.String'.
更新:我发现EF生成SQL查询,真正返回一个字符串作为实体的一个标识符。
行进至DB ((query as ObjectQuery).ToTraceString())
的SQL是这样的:
SELECT
[UnionAll1].[C2] AS [C1],
[UnionAll1].[C3] AS [C2],
[UnionAll1].[Id] AS [C3],
[UnionAll1].[PfrRegNumber] AS [C4],
[UnionAll1].[PfrUnitId] AS [C5],
[UnionAll1].[Account_Id] AS [C6],
[UnionAll1].[ActiveCertificate_Id] AS [C7],
[UnionAll1].[C1] AS [C8],
[UnionAll1].[Id1] AS [C9],
[UnionAll1].[C4] AS [C10]
FROM (SELECT
CASE WHEN ([Extent2].[Id] IS NULL) THEN NULL ELSE 1 END AS [C1],
1 AS [C2],
1 AS [C3],
[Extent1].[Id] AS [Id],
[Extent1].[PfrRegNumber] AS [PfrRegNumber],
[Extent1].[PfrUnitId] AS [PfrUnitId],
[Extent1].[Account_Id] AS [Account_Id],
[Extent1].[ActiveCertificate_Id] AS [ActiveCertificate_Id],
[Extent2].[Id] AS [Id1],
NULL AS [C4]
FROM [AbonentPfrs] AS [Extent1]
LEFT OUTER JOIN [Certificates] AS [Extent2] ON [Extent1].[Id] = [Extent2].[AbonentPfr_PfrCertificates_Certificate_Id]
UNION ALL
SELECT
2 AS [C1],
2 AS [C2],
2 AS [C3],
[Extent3].[Id] AS [Id],
[Extent3].[PfrRegNumber] AS [PfrRegNumber],
[Extent3].[PfrUnitId] AS [PfrUnitId],
[Extent3].[Account_Id] AS [Account_Id],
[Extent3].[ActiveCertificate_Id] AS [ActiveCertificate_Id],
NULL AS [C4],
[Extent4].[Id] AS [Id1]
FROM [AbonentPfrs] AS [Extent3]
INNER JOIN [Certificates] AS [Extent4] ON [Extent3].[Id] = [Extent4].[AbonentPfr_AcCertificates_Certificate_Id]) AS [UnionAll1]
ORDER BY [UnionAll1].[Id] ASC, [UnionAll1].[C1] ASC
的最后列的证书中的实体ID。但最后有Guid类型和之前的字符串。如果我单独运行查询的部分,然后我得到的下一列类型(FOT最后两个):
- 首先选择:GUID,对象
- 第二个选择:对象,的Guid
- UNION ALL:GUID,对象
- 外选择:字符串的Guid
为什么在倒数第二个栏外select返回字符串?
我认为这是因为两个关系在同一个表上 - 从AbonentPfr到证书。但我不确定... – sedovav
可能是因为SQLite存储GUID作为字符串? AFAIK SQLite没有本地GUID数据类型。 – okrumnow
但在所有其他查询中,它的工作原理相同 – sedovav