Entity Framework存在一些问题,在迁移过程中没有调用“种子”方法。经过相当多的努力,我把它归结为当它调用HistoryRepositor.GetLastModel(https://github.com/aspnet/EntityFramework6/blob/master/src/EntityFramework/Migrations/History/HistoryRepository.cs)时。特别是本节;
var baseQuery
= CreateHistoryQuery(context, contextKey)
.OrderByDescending(h => h.MigrationId);
var lastModel
= baseQuery
.Select(
s => new
{
s.MigrationId,
s.Model,
s.ProductVersion
})
.FirstOrDefault();
'baseQuery'的值如下所示。
{SELECT
[Project1].[MigrationId] AS [MigrationId],
[Project1].[ContextKey] AS [ContextKey],
[Project1].[Model] AS [Model],
[Project1].[ProductVersion] AS [ProductVersion]
FROM ( SELECT
[Extent1].[MigrationId] AS [MigrationId],
[Extent1].[ContextKey] AS [ContextKey],
[Extent1].[Model] AS [Model],
[Extent1].[ProductVersion] AS [ProductVersion]
FROM [__MigrationHistory] AS [Extent1]
WHERE [Extent1].[ContextKey] = @p__linq__0
) AS [Project1]
ORDER BY [Project1].[MigrationId] DESC}
MigrationHistory表中有两条记录,似乎是通过在即时窗口中使用'baseQuery.ToList()'来确认的,并且顺序正确(MigrationId降序 - 这些是时间戳,因此应该是最新的记录)
baseQuery.ToList()[0];
{System.Data.Entity.Migrations.History.HistoryRow}
ContextKey: "DT.DataAccess.AppContext"
MigrationId: "201612011150460_AutomaticMigration"
Model: {byte[5615]}
ProductVersion: "6.1.0-alpha1"
baseQuery.ToList()[1];
{System.Data.Entity.Migrations.History.HistoryRow}
ContextKey: "DT.DataAccess.AppContext"
MigrationId: "201611291632453_AutomaticMigration"
Model: {byte[5592]}
ProductVersion: "6.1.3-40302"
但是,分配给lastModel的记录不是“201612011150460_AutomaticMigration”,而是“201611291632453_AutomaticMigration”,这是意外的。
lastModel = { MigrationId = "201611291632453_AutomaticMigration", Model = {byte[5592]}, ProductVersion = "6.1.3-40302" }
使用立即窗口中的baseQuery.FirstOrDefault();
(或First()
);
baseQuery.FirstOrDefault();
{System.Data.Entity.Migrations.History.HistoryRow}
ContextKey: "DT.DataAccess.AppContext"
MigrationId: "201611291632453_AutomaticMigration"
Model: {byte[5592]}
ProductVersion: "6.1.3-40302"
使用baseQuery
创建OrderByDescending
时,这应该意味着它是固定的顺序,对吗?