EF Core 7多Include查询引发Departures实体重复枚举问题
EF Core 7升级后关联Departures出现重复条目问题
我们有对应的数据库架构,测试场景为查找Connection并验证其关联所有Departures的Id唯一性。EF Core 6中一切正常,每个Departure条目仅出现一次;但升级至EF Core 7(7.0.0或7.0.2)后,部分Departures重复出现,导致验证Id唯一性的测试失败。
测试代码
// ...preparing DI this.lines = scope.ServiceProvider.GetRequiredService<ILinesRepository>(); lines.Load(); // heavy task loading the data into memory for about 2 minutes (i know it's not really good but it's not my code...) var connection = lines.GetConnection(lineNumber, connectionNumber); // filtering the data loaded in previous step var groups = connection.Departures.GroupBy(d => d.Id); // finding the number of distinct IDs Assert.Equal(groups.Count(), connection.Departures.Count);
lines.Load(DateTime? forDate = null)方法代码
var date = forDate ?? DateTime.Today; // ... fetching some other data _departures = DeparturesSet .Include(d => d.TariffStation) .ThenInclude(ts => ts.BackwardPlatform) .Include(d => d.TariffStation) .ThenInclude(ts => ts.ForwardPlatform) .Include(d => d.TariffStation) .ThenInclude(ts => ts.Station) .Include(d => d.Connection) .ThenInclude(l => l.Line) .ThenInclude(l => l.Validity) .Where(d => !d.Connection.Line.ValidTo.HasValue || d.Connection.Line.ValidTo.Value >= date) .AsSplitQuery() .ToArray(); // ... fetching some other data
ConnectionEntity? GetConnection(long lineNumber, int connectionNumber)方法代码
_departures?.FirstOrDefault(d => d.Connection.Line.IsValid(DateTime.Now) && d.Connection.Number == connectionNumber && d.Connection.Line.Number == lineNumber)?.Connection;
排查情况
尝试注释掉_departures查询中的不同部分,仅保留Connection和Line的Include(否则测试会因空引用失败)。只要查询中包含至少一个.Include(d => d.TariffStation)(即使没有ThenInclude部分),测试就会失败。
看起来被Include的TariffStation还会获取所有关联的Departures,但这在实体类和映射中均未定义。
TariffStationEntity与DepartureEntity的关联配置(b为DepartureEntity)
builder.HasOne(b => b.TariffStation) .WithMany() .HasForeignKey(b => b.TariffStationId) .OnDelete(DeleteBehavior.Restrict);
内容的提问来源于stack exchange,提问作者Nomen
相关产品推荐
相关产品推荐

