我只是想用EntityFramework加载一些带有各自“Domains”的“EventTypes”。关系是N:1,即EventType引用具有列EventType.DomainID的域。
这很有效。
IEnumerable data = await dbContext.EventTypes
.Include(x => x.Domain) .ToListAsync();
它产生的SQL代码:
SELECT [x].[ID], [x].[DomainID], [x].[HtmlEventDescription], [x].[Name], [x].[Url], [d].[ID], [d].[DebugHost], [d].[Host]
FROM [EventTypes] AS [x]
INNER JOIN [Domains] AS [d] ON [x].[DomainID] = [d].[ID]
但现在我想加入分页。
IEnumerable data = await dbContext.EventTypes.Include(x => x.Domain) .Take(pageSize)
.Skip(pageIndex * 10) .ToListAsync();
它生成的SQL没问题,在SQL管理器中尝试过它,但它只返回域的列。
SELECT [d].[ID], [d].[DebugHost], [d].[Host]
FROM (
SELECT TOP(@__p_0) [x].[ID], [x].[DomainID], [x].[HtmlEventDescription], [x].[Name], [x].[Url]
FROM [EventTypes] AS [x]
) AS [t]
INNER JOIN [Domains] AS [d] ON [t].[DomainID] = [d].[ID]
ORDER BY (SELECT 1)
OFFSET @__p_1 ROWS
但现在它也会产生异常。
Microsoft.EntityFrameworkCore.Query.Internal.SqlServerQueryCompilationContextFactory:Error: An exception occurred in the database while iterating the results of a query.
System.InvalidOperationException: An exception occured while reading a database value for property 'EventType.DomainID'. The expected type was 'System.Int32' but the actual value was of type 'System.String'. ---> System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Int32'.
我想知道我做错了什么。
为什么EF创建一个只有“Domain”属性的查询,尽管我在查询带有dbContext.EventTypes
的EventTypes表?我怀疑这就是为什么它试图将字符串转换为int,因为结果中首先没有DomainID列,它可能会尝试将Domain.DebugHost
或Debug.Host
的字符串列强制转换为{{1 }}
答案 0 :(得分:2)
我在评论中被告知:
错误就是这些行
.Take(pageSize)
.Skip(pageIndex * 10)
必须采用不同的顺序。跳过必须在Take之前。现在它正常工作。
.Skip(pageIndex * pageSize)
.Take(pageSize)