Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 18 additions & 16 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -1170,6 +1170,8 @@ Entity Framework never tracks a keyless entity type, so `AsNoTracking()` or `AsT

`AsSplitQuery()` and `AsSingleQuery()` only change how collections are loaded, by a collection `Include` or a collection in a projection. On a query that loads no collection they do nothing. A single collection is enough for `AsSplitQuery()` to have an effect, since it then avoids repeating the parent columns for each child row.

An entity the query returns brings collections with it, that EF loads without an `Include`, and those count: the collections it owns, other than ones mapped to JSON, and those configured with `AutoInclude`, unless the query uses `IgnoreAutoIncludes()`.

<!-- snippet: IgnoredSplitQuery -->
<a id='snippet-IgnoredSplitQuery'></a>
```cs
Expand Down Expand Up @@ -1244,7 +1246,7 @@ await ThrowsTask(() =>
.CountAsync())
.IgnoreStackTrace();
```
<sup><a href='/src/Verify.EntityFramework.Tests/AntiPatternTests.cs#L898-L906' title='Snippet source file'>snippet source</a> | <a href='#snippet-OrderByThenCount' title='Start of snippet'>anchor</a></sup>
<sup><a href='/src/Verify.EntityFramework.Tests/AntiPatternTests.cs#L1006-L1014' title='Snippet source file'>snippet source</a> | <a href='#snippet-OrderByThenCount' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->

So does `GroupBy`. Unlike LINQ to objects, Entity Framework drops an ordering before a `GroupBy`, so it orders neither the groups nor the elements in them, and `First()` of a group picks by primary key, not by that ordering:
Expand All @@ -1260,7 +1262,7 @@ await ThrowsTask(() =>
.ToListAsync())
.IgnoreStackTrace();
```
<sup><a href='/src/Verify.EntityFramework.Tests/AntiPatternTests.cs#L978-L988' title='Snippet source file'>snippet source</a> | <a href='#snippet-OrderByThenGroupBy' title='Start of snippet'>anchor</a></sup>
<sup><a href='/src/Verify.EntityFramework.Tests/AntiPatternTests.cs#L1086-L1096' title='Snippet source file'>snippet source</a> | <a href='#snippet-OrderByThenGroupBy' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->

Throws:
Expand Down Expand Up @@ -1292,7 +1294,7 @@ await ThrowsTask(() =>
.ExecuteDeleteAsync())
.IgnoreStackTrace();
```
<sup><a href='/src/Verify.EntityFramework.Tests/AntiPatternTests.cs#L1032-L1041' title='Snippet source file'>snippet source</a> | <a href='#snippet-OrderByThenExecuteDelete' title='Start of snippet'>anchor</a></sup>
<sup><a href='/src/Verify.EntityFramework.Tests/AntiPatternTests.cs#L1140-L1149' title='Snippet source file'>snippet source</a> | <a href='#snippet-OrderByThenExecuteDelete' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->

Throws:
Expand Down Expand Up @@ -1359,7 +1361,7 @@ await ThrowsTask(() =>
.ToListAsync())
.IgnoreStackTrace();
```
<sup><a href='/src/Verify.EntityFramework.Tests/AntiPatternTests.cs#L1084-L1092' title='Snippet source file'>snippet source</a> | <a href='#snippet-CountGreaterThanZero' title='Start of snippet'>anchor</a></sup>
<sup><a href='/src/Verify.EntityFramework.Tests/AntiPatternTests.cs#L1192-L1200' title='Snippet source file'>snippet source</a> | <a href='#snippet-CountGreaterThanZero' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->

Throws:
Expand Down Expand Up @@ -1399,7 +1401,7 @@ await ThrowsTask(() =>
.ToListAsync())
.IgnoreStackTrace();
```
<sup><a href='/src/Verify.EntityFramework.Tests/AntiPatternTests.cs#L1132-L1146' title='Snippet source file'>snippet source</a> | <a href='#snippet-DistinctOnKey' title='Start of snippet'>anchor</a></sup>
<sup><a href='/src/Verify.EntityFramework.Tests/AntiPatternTests.cs#L1240-L1254' title='Snippet source file'>snippet source</a> | <a href='#snippet-DistinctOnKey' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->

Throws:
Expand Down Expand Up @@ -1434,7 +1436,7 @@ await ThrowsTask(() =>
.ToListAsync())
.IgnoreStackTrace();
```
<sup><a href='/src/Verify.EntityFramework.Tests/AntiPatternTests.cs#L1228-L1237' title='Snippet source file'>snippet source</a> | <a href='#snippet-GroupByOnlyKey' title='Start of snippet'>anchor</a></sup>
<sup><a href='/src/Verify.EntityFramework.Tests/AntiPatternTests.cs#L1336-L1345' title='Snippet source file'>snippet source</a> | <a href='#snippet-GroupByOnlyKey' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->

Throws:
Expand Down Expand Up @@ -1473,7 +1475,7 @@ await ThrowsTask(() =>
.ToListAsync())
.IgnoreStackTrace();
```
<sup><a href='/src/Verify.EntityFramework.Tests/AntiPatternTests.cs#L1291-L1304' title='Snippet source file'>snippet source</a> | <a href='#snippet-UnorderedFirst' title='Start of snippet'>anchor</a></sup>
<sup><a href='/src/Verify.EntityFramework.Tests/AntiPatternTests.cs#L1399-L1412' title='Snippet source file'>snippet source</a> | <a href='#snippet-UnorderedFirst' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->

Throws:
Expand Down Expand Up @@ -1507,7 +1509,7 @@ await Throws(() =>
.ToQueryString())
.IgnoreStackTrace();
```
<sup><a href='/src/Verify.EntityFramework.Tests/AntiPatternTests.cs#L1674-L1682' title='Snippet source file'>snippet source</a> | <a href='#snippet-IncludeOwnedNavigation' title='Start of snippet'>anchor</a></sup>
<sup><a href='/src/Verify.EntityFramework.Tests/AntiPatternTests.cs#L1782-L1790' title='Snippet source file'>snippet source</a> | <a href='#snippet-IncludeOwnedNavigation' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->

Throws:
Expand Down Expand Up @@ -1539,7 +1541,7 @@ await ThrowsTask(() =>
.ToListAsync())
.IgnoreStackTrace();
```
<sup><a href='/src/Verify.EntityFramework.Tests/AntiPatternTests.cs#L1701-L1710' title='Snippet source file'>snippet source</a> | <a href='#snippet-DuplicateInclude' title='Start of snippet'>anchor</a></sup>
<sup><a href='/src/Verify.EntityFramework.Tests/AntiPatternTests.cs#L1809-L1818' title='Snippet source file'>snippet source</a> | <a href='#snippet-DuplicateInclude' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->

Throws:
Expand Down Expand Up @@ -1573,7 +1575,7 @@ var builder = new DbContextOptionsBuilder<ShopContext>();
builder.UseSqlServer(connectionString);
builder.ThrowOnAntiPatterns(_ => _.ThrowOnIgnoredQueryFilters = true);
```
<sup><a href='/src/Verify.EntityFramework.Tests/AntiPatternTests.cs#L1910-L1916' title='Snippet source file'>snippet source</a> | <a href='#snippet-ThrowOnIgnoredQueryFilters' title='Start of snippet'>anchor</a></sup>
<sup><a href='/src/Verify.EntityFramework.Tests/AntiPatternTests.cs#L2018-L2024' title='Snippet source file'>snippet source</a> | <a href='#snippet-ThrowOnIgnoredQueryFilters' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->

<!-- snippet: IgnoreQueryFiltersWithoutFilter -->
Expand All @@ -1585,7 +1587,7 @@ await Throws(() =>
.ToQueryString())
.IgnoreStackTrace();
```
<sup><a href='/src/Verify.EntityFramework.Tests/AntiPatternTests.cs#L1761-L1769' title='Snippet source file'>snippet source</a> | <a href='#snippet-IgnoreQueryFiltersWithoutFilter' title='Start of snippet'>anchor</a></sup>
<sup><a href='/src/Verify.EntityFramework.Tests/AntiPatternTests.cs#L1869-L1877' title='Snippet source file'>snippet source</a> | <a href='#snippet-IgnoreQueryFiltersWithoutFilter' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->

Throws:
Expand Down Expand Up @@ -1617,7 +1619,7 @@ var builder = new DbContextOptionsBuilder<SampleDbContext>();
builder.UseInMemoryDatabase(databaseName);
builder.ThrowOnAntiPatterns(_ => _.ThrowOnCollectionFilterOutsideInclude = true);
```
<sup><a href='/src/Verify.EntityFramework.Tests/AntiPatternTests.cs#L1978-L1984' title='Snippet source file'>snippet source</a> | <a href='#snippet-ThrowOnCollectionFilterOutsideInclude' title='Start of snippet'>anchor</a></sup>
<sup><a href='/src/Verify.EntityFramework.Tests/AntiPatternTests.cs#L2158-L2164' title='Snippet source file'>snippet source</a> | <a href='#snippet-ThrowOnCollectionFilterOutsideInclude' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->

<!-- snippet: CollectionFilterOutsideInclude -->
Expand All @@ -1630,7 +1632,7 @@ await ThrowsTask(() =>
.ToListAsync())
.IgnoreStackTrace();
```
<sup><a href='/src/Verify.EntityFramework.Tests/AntiPatternTests.cs#L1629-L1638' title='Snippet source file'>snippet source</a> | <a href='#snippet-CollectionFilterOutsideInclude' title='Start of snippet'>anchor</a></sup>
<sup><a href='/src/Verify.EntityFramework.Tests/AntiPatternTests.cs#L1737-L1746' title='Snippet source file'>snippet source</a> | <a href='#snippet-CollectionFilterOutsideInclude' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->

Throws:
Expand Down Expand Up @@ -1665,7 +1667,7 @@ var builder = new DbContextOptionsBuilder<SampleDbContext>();
builder.UseInMemoryDatabase(databaseName);
builder.ThrowOnAntiPatterns(_ => _.ThrowOnColumnCaseConversion = true);
```
<sup><a href='/src/Verify.EntityFramework.Tests/AntiPatternTests.cs#L1466-L1472' title='Snippet source file'>snippet source</a> | <a href='#snippet-ThrowOnColumnCaseConversion' title='Start of snippet'>anchor</a></sup>
<sup><a href='/src/Verify.EntityFramework.Tests/AntiPatternTests.cs#L1574-L1580' title='Snippet source file'>snippet source</a> | <a href='#snippet-ThrowOnColumnCaseConversion' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->

<!-- snippet: ToLowerInWhere -->
Expand All @@ -1677,7 +1679,7 @@ await ThrowsTask(() =>
.ToListAsync())
.IgnoreStackTrace();
```
<sup><a href='/src/Verify.EntityFramework.Tests/AntiPatternTests.cs#L1406-L1414' title='Snippet source file'>snippet source</a> | <a href='#snippet-ToLowerInWhere' title='Start of snippet'>anchor</a></sup>
<sup><a href='/src/Verify.EntityFramework.Tests/AntiPatternTests.cs#L1514-L1522' title='Snippet source file'>snippet source</a> | <a href='#snippet-ToLowerInWhere' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->

Throws:
Expand Down Expand Up @@ -1786,7 +1788,7 @@ await ThrowsTask(() =>
.ToListAsync())
.IgnoreStackTrace();
```
<sup><a href='/src/Verify.EntityFramework.Tests/AntiPatternTests.cs#L1839-L1847' title='Snippet source file'>snippet source</a> | <a href='#snippet-RequiredNullCheck' title='Start of snippet'>anchor</a></sup>
<sup><a href='/src/Verify.EntityFramework.Tests/AntiPatternTests.cs#L1947-L1955' title='Snippet source file'>snippet source</a> | <a href='#snippet-RequiredNullCheck' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->

Throws:
Expand Down
1 change: 1 addition & 0 deletions src/Shared.sln.DotSettings
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=RedundantUsingDirective/@EntryIndexedValue">ERROR</s:String>
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=RedundantVerbatimPrefix/@EntryIndexedValue">ERROR</s:String>
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=RedundantVerbatimStringPrefix/@EntryIndexedValue">ERROR</s:String>
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=ReplaceSequenceEqualWithConstantPattern/@EntryIndexedValue">ERROR</s:String>
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=SealedMemberInSealedClass/@EntryIndexedValue">ERROR</s:String>
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=ThreadStaticFieldHasInitializer/@EntryIndexedValue">ERROR</s:String>
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=UnnecessaryWhitespace/@EntryIndexedValue">ERROR</s:String>
Expand Down
180 changes: 180 additions & 0 deletions src/Verify.EntityFramework.Tests/AntiPatternTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -799,6 +799,114 @@ public void SplitQueryKept()
.ToQueryString();
}

// an entity brings the collections it owns, and those configured with AutoInclude, without an Include
[Test]
public void SplitQueryKeptForCollectionOfReturnedEntity()
{
using var shops = BuildShopData();

// Staff is configured with AutoInclude
shops.Shops
.AsSplitQuery()
.ToQueryString();

shops.Shops
.AsSingleQuery()
.Where(_ => _.Id > 1)
.ToQueryString();

using var data = BuildDepotData();

// Phones is owned
data.Depots
.AsSplitQuery()
.ToQueryString();

// Office is owned, and owns Phones
data.Yards
.AsSplitQuery()
.ToQueryString();

// the entity is returned by a projection
data.Trucks
.AsSplitQuery()
.Select(_ => _.Depot)
.ToQueryString();

data.Trucks
.AsSplitQuery()
.Select(_ => new
{
_.Id,
_.Depot
})
.ToQueryString();
}

// Phone is owned by more than one type, so the model has an entity type for each owner
[Test]
public void SplitQueryKeptForCollectionOfTypeWithManyOwners()
{
using var data = BuildDepotData();

// not tracked, since EF does not track an owned entity without its owner
data.Depots
.AsNoTracking()
.AsSplitQuery()
.Select(_ => new
{
_.Name,
Phones = _.Phones.ToList()
})
.ToQueryString();
}

[Test]
public async Task SplitQueryWithoutCollectionOfReturnedEntity()
{
await using var shops = BuildShopData();

// IgnoreAutoIncludes stops EF loading Staff
await AssertSplittingIgnored(
shops.Shops
.IgnoreAutoIncludes()
.AsSplitQuery());

await using var data = BuildDepotData();

// the entity that owns Phones is not returned
await AssertSplittingIgnored(
data.Depots
.AsSplitQuery()
.Select(_ => _.Name));

// a new instance only has what the projection gives it
await AssertSplittingIgnored(
data.Depots
.AsSplitQuery()
.Select(_ => new Depot
{
Name = _.Name
}));

// Entries is mapped to JSON, so it is a column of its owner
await AssertSplittingIgnored(
data.Journals
.AsSplitQuery());

// Truck brings no collection, and Depot is only read
await AssertSplittingIgnored(
data.Trucks
.AsSplitQuery()
.Where(_ => _.Depot.Name != ""));
}

static async Task AssertSplittingIgnored(IQueryable query)
{
var exception = Assert.ThrowsExactly<Exception>(() => query.ToQueryString());
await Assert.That(exception.Message).StartsWith("AsSplitQuery() is ignored");
}

// a model anti-pattern, logged when the model is built
[Test]
public async Task BoolWithDefault()
Expand Down Expand Up @@ -1973,6 +2081,78 @@ class ShopView
public string Name { get; set; } = "";
}

static DepotContext BuildDepotData()
{
var builder = new DbContextOptionsBuilder<DepotContext>();
builder.UseSqlServer(connectionString);
builder.ThrowOnAntiPatterns();
builder.EnableServiceProviderCaching(false);
return new(builder.Options);
}

class DepotContext(DbContextOptions options) :
DbContext(options)
{
public DbSet<Depot> Depots => Set<Depot>();
public DbSet<Yard> Yards => Set<Yard>();
public DbSet<Truck> Trucks => Set<Truck>();
public DbSet<Journal> Journals => Set<Journal>();

protected override void OnModelCreating(ModelBuilder model)
{
model
.Entity<Depot>()
.OwnsMany(_ => _.Phones);
model
.Entity<Yard>()
.OwnsOne(_ => _.Office, _ => _.OwnsMany(_ => _.Phones));
model
.Entity<Journal>()
.OwnsMany(_ => _.Entries, _ => _.ToJson());
}
}

class Depot
{
public int Id { get; set; }
public string Name { get; set; } = "";
public List<Phone> Phones { get; set; } = [];
}

class Yard
{
public int Id { get; set; }
public Office? Office { get; set; }
}

class Office
{
public string Name { get; set; } = "";
public List<Phone> Phones { get; set; } = [];
}

class Phone
{
public string Number { get; set; } = "";
}

class Truck
{
public int Id { get; set; }
public Depot Depot { get; set; } = null!;
}

class Journal
{
public int Id { get; set; }
public List<JournalEntry> Entries { get; set; } = [];
}

class JournalEntry
{
public string Text { get; set; } = "";
}

static SampleDbContext BuildCollectionFilterData([CallerMemberName] string databaseName = "")
{
#region ThrowOnCollectionFilterOutsideInclude
Expand Down
Loading