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
Original file line number Diff line number Diff line change
Expand Up @@ -1420,6 +1420,11 @@ void ProcessType(StructuralTypeProjectionExpression typeProjection)
continue;
}

if (!property.IsAutoLoaded)
{
continue;
}

projections[property] = AddToProjection(typeProjection.BindProperty(property), alias: null);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,6 @@ protected override bool ShouldBeAutoLoaded(IConventionProperty property)
// If there's a value converter, the CLR type may not reflect the store type,
// so we can only check for SqlVector<> when there's no converter.
return property.GetValueConverter() is not null
|| property.ClrType.TryGetElementType(typeof(SqlVector<>)) is null;
|| property.ClrType.UnwrapNullableType().TryGetElementType(typeof(SqlVector<>)) is null;
}
}
28 changes: 27 additions & 1 deletion src/EFCore/Infrastructure/ModelValidator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public virtual void Validate(IModel model, IDiagnosticsLogger<DbLoggerCategory.M
ValidateEntityType(entityType, logger);
ValidateClrInheritance(entityType, validEntityTypes);
ValidateData(entityType, identityMaps, sensitiveDataLogged, logger);

var primaryKey = entityType.FindPrimaryKey();
if (primaryKey == null)
{
Expand Down Expand Up @@ -99,6 +99,7 @@ protected virtual void ValidateEntityType(
ValidateInheritanceMapping(entityType, logger);
ValidateFieldMapping(entityType, logger);
ValidateQueryFilters(entityType, logger);
ValidateConstructorBindingAutoLoaded(entityType);

foreach (var property in entityType.GetDeclaredProperties())
{
Expand Down Expand Up @@ -138,6 +139,30 @@ protected virtual void ValidateEntityType(
LogShadowProperties(entityType, logger);
}

/// <summary>
/// Validates that no constructor-bound property is configured as not auto-loaded.
/// </summary>
/// <param name="structuralType">The structural type to validate.</param>
protected virtual void ValidateConstructorBindingAutoLoaded(ITypeBase structuralType)
{
if (structuralType.ConstructorBinding is null)
{
return;
}

var typeName = structuralType.DisplayName();

foreach (var consumedProperty in structuralType.ConstructorBinding.ParameterBindings
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Move this to ValidateAutoLoaded since it's rare to have a non-autoloaded property

.SelectMany(p => p.ConsumedProperties))
{
if (consumedProperty is IProperty { IsAutoLoaded: false } property)
{
throw new InvalidOperationException(
CoreStrings.AutoLoadedConstructorProperty(property.Name, typeName));
}
}
}

/// <summary>
/// Validates inheritance mapping for an entity type.
/// </summary>
Expand Down Expand Up @@ -226,6 +251,7 @@ protected virtual void ValidateComplexProperty(
var complexType = complexProperty.ComplexType;

ValidateChangeTrackingStrategy(complexType, logger);
ValidateConstructorBindingAutoLoaded(complexType);

foreach (var property in complexType.GetDeclaredProperties())
{
Expand Down
8 changes: 8 additions & 0 deletions src/EFCore/Properties/CoreStrings.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

57 changes: 30 additions & 27 deletions src/EFCore/Properties/CoreStrings.resx
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
<!--
Microsoft ResX Schema

Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes

The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.

Example:

... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
Expand All @@ -26,36 +26,36 @@
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple

There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the

Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not

The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can

Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.

mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.

mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.

mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
Expand Down Expand Up @@ -168,6 +168,9 @@
<data name="AutoLoadedConcurrencyTokenProperty" xml:space="preserve">
<value>The property '{property}' on type '{type}' is a concurrency token and cannot be configured as not auto-loaded. Concurrency tokens must always be loaded.</value>
</data>
<data name="AutoLoadedConstructorProperty" xml:space="preserve">
<value>The property '{property}' on type '{type}' is used in a constructor binding and cannot be configured as not auto-loaded. Constructor-bound properties must always be loaded.</value>
</data>
<data name="AutoLoadedDiscriminatorProperty" xml:space="preserve">
<value>The property '{property}' on type '{type}' is a discriminator and cannot be configured as not auto-loaded. Discriminator properties must always be loaded.</value>
</data>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public Expression CreateMaterializeExpression(
bindingInfo.ServiceInstances.Add(instanceVariable);

var properties = new HashSet<IPropertyBase>(
structuralType.GetProperties().Cast<IPropertyBase>().Where(p => !p.IsShadowProperty())
structuralType.GetProperties().Cast<IPropertyBase>().Where(p => !p.IsShadowProperty() && p is not IProperty { IsAutoLoaded: false })
.Concat(structuralType.GetComplexProperties().Where(p => !p.IsShadowProperty())));
Comment on lines +78 to 79
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
structuralType.GetProperties().Cast<IPropertyBase>().Where(p => !p.IsShadowProperty() && p is not IProperty { IsAutoLoaded: false })
.Concat(structuralType.GetComplexProperties().Where(p => !p.IsShadowProperty())));
structuralType.GetProperties().Where(p => !p.IsShadowProperty() && !p.IsAutoLoaded).Cast<IPropertyBase>()
.Concat(structuralType.GetComplexProperties().Where(p => !p.IsShadowProperty())));


var blockExpressions = new List<Expression>();
Expand Down
6 changes: 4 additions & 2 deletions src/EFCore/Query/ShapedQueryCompilingExpressionVisitor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -754,8 +754,10 @@ private BlockExpression CreateFullMaterializeExpression(
shadowProperties.Select(
p =>
Convert(
valueBufferExpression.CreateValueBufferReadValueExpression(
p.ClrType, p.GetIndex(), p), typeof(object)))))));
p is IProperty { IsAutoLoaded: false }
? (p.Sentinel is null ? Default(p.ClrType) : Constant(p.Sentinel, p.ClrType))
: valueBufferExpression.CreateValueBufferReadValueExpression(
p.ClrType, p.GetIndex(), p), typeof(object)))))));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,16 @@ await ExecuteWithStrategyInTransactionAsync(
{
var blog = await context.Set<BlogWithDescription>().SingleAsync();
Assert.Equal("Updated Blog", blog.Name);
Assert.Equal("Original description", blog.Description);

// Description is not auto-loaded, so it should be null (sentinel) in the materialized entity
Assert.Null(blog.Description);

// Verify the data is correct in the database by explicitly projecting the non-auto-loaded property
var description = await context.Set<BlogWithDescription>()
.Where(b => b.Description == "Original description")
.Select(b => b.Description)
.SingleAsync();
Assert.Equal("Original description", description);
});
}

Expand Down Expand Up @@ -198,7 +207,144 @@ await ExecuteWithStrategyInTransactionAsync(
{
var blog = await context.Set<BlogWithTags>().SingleAsync();
Assert.Equal("Updated Blog", blog.Name);
Assert.Equal(new[] { "efcore", "dotnet" }, blog.Tags);
// Tags is not auto-loaded, so it should be the empty sentinel in the materialized entity
Assert.Empty(blog.Tags);
});
}

[ConditionalTheory, MemberData(nameof(IsAsyncData))]
public virtual async Task Query_with_not_auto_loaded_property_tracked(bool async)
{
var contextFactory = await InitializeNonSharedTest<DbContext>(
onModelCreating: mb => mb.Entity<BlogWithDescription>(
b => b.Property(e => e.Description).Metadata.IsAutoLoaded = false),
seed: async context =>
{
context.Add(new BlogWithDescription { Name = "EF Blog", Description = "Some description" });
await context.SaveChangesAsync();
});

await ExecuteWithStrategyInTransactionAsync(
contextFactory,
async context =>
{
var blog = async
? await context.Set<BlogWithDescription>().SingleAsync()
: context.Set<BlogWithDescription>().Single();

// The non-auto-loaded property should not have been fetched
Assert.Null(blog.Description);

// The change tracker should know the property is not loaded
var entry = context.Entry(blog);
Assert.False(entry.Property(e => e.Description).IsLoaded);
});
}

[ConditionalTheory, MemberData(nameof(IsAsyncData))]
public virtual async Task Query_with_not_auto_loaded_property_no_tracking(bool async)
{
var contextFactory = await InitializeNonSharedTest<DbContext>(
onModelCreating: mb => mb.Entity<BlogWithDescription>(
b => b.Property(e => e.Description).Metadata.IsAutoLoaded = false),
seed: async context =>
{
context.Add(new BlogWithDescription { Name = "EF Blog", Description = "Some description" });
await context.SaveChangesAsync();
});

await ExecuteWithStrategyInTransactionAsync(
contextFactory,
async context =>
{
var blog = async
? await context.Set<BlogWithDescription>().AsNoTracking().SingleAsync()
: context.Set<BlogWithDescription>().AsNoTracking().Single();

// The non-auto-loaded property should not have been fetched, and retains its default/sentinel value
Assert.Null(blog.Description);
});
}

[ConditionalTheory, MemberData(nameof(IsAsyncData))]
public virtual async Task Explicit_select_of_not_auto_loaded_property(bool async)
{
var contextFactory = await InitializeNonSharedTest<DbContext>(
onModelCreating: mb => mb.Entity<BlogWithDescription>(
b => b.Property(e => e.Description).Metadata.IsAutoLoaded = false),
seed: async context =>
{
context.Add(new BlogWithDescription { Name = "EF Blog", Description = "Some description" });
await context.SaveChangesAsync();
});

await ExecuteWithStrategyInTransactionAsync(
contextFactory,
async context =>
{
// Explicitly projecting the non-auto-loaded property should still work
var description = async
? await context.Set<BlogWithDescription>().Select(b => b.Description).SingleAsync()
: context.Set<BlogWithDescription>().Select(b => b.Description).Single();

Assert.Equal("Some description", description);
});
}

[ConditionalTheory, MemberData(nameof(IsAsyncData))]
public virtual async Task Where_on_not_auto_loaded_property(bool async)
{
var contextFactory = await InitializeNonSharedTest<DbContext>(
onModelCreating: mb => mb.Entity<BlogWithDescription>(
b => b.Property(e => e.Description).Metadata.IsAutoLoaded = false),
seed: async context =>
{
context.Add(new BlogWithDescription { Name = "EF Blog", Description = "Some description" });
await context.SaveChangesAsync();
});

await ExecuteWithStrategyInTransactionAsync(
contextFactory,
async context =>
{
// Filtering on a non-auto-loaded property should work; the property must be available in the subquery
var blog = async
? await context.Set<BlogWithDescription>().Where(b => b.Description == "Some description").SingleAsync()
: context.Set<BlogWithDescription>().Where(b => b.Description == "Some description").Single();

Assert.Equal("EF Blog", blog.Name);

// The non-auto-loaded property should still not be in the entity projection
Assert.Null(blog.Description);
});
}

[ConditionalTheory, MemberData(nameof(IsAsyncData))]
public virtual async Task Query_with_not_auto_loaded_primitive_collection(bool async)
{
var contextFactory = await InitializeNonSharedTest<DbContext>(
onModelCreating: mb => mb.Entity<BlogWithTags>(
b =>
{
b.Property(e => e.Tags).Metadata.IsAutoLoaded = false;
b.Property(e => e.Tags).Metadata.Sentinel = new List<string>();
}),
seed: async context =>
{
context.Add(new BlogWithTags { Name = "EF Blog", Tags = ["efcore", "dotnet"] });
await context.SaveChangesAsync();
});

await ExecuteWithStrategyInTransactionAsync(
contextFactory,
async context =>
{
var blog = async
? await context.Set<BlogWithTags>().SingleAsync()
: context.Set<BlogWithTags>().Single();

// The non-auto-loaded primitive collection should not have been fetched
Assert.Empty(blog.Tags);
});
}

Expand Down
Loading
Loading