Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update handling for bools and enums with database defaults #30843

Merged
merged 3 commits into from
May 9, 2023
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
19 changes: 16 additions & 3 deletions src/EFCore.Relational/Diagnostics/RelationalLoggerExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2505,7 +2505,14 @@ public static void BoolWithDefaultWarning(

if (diagnostics.ShouldLog(definition))
{
definition.Log(diagnostics, property.Name, property.DeclaringEntityType.DisplayName());
var defaultValue = property.ClrType.GetDefaultValue();
definition.Log(
diagnostics,
property.ClrType.ShortDisplayName(),
property.Name,
property.DeclaringEntityType.DisplayName(),
defaultValue == null ? "null" : defaultValue.ToString()!,
property.ClrType.ShortDisplayName());
}

if (diagnostics.NeedsEventData(definition, out var diagnosticSourceEnabled, out var simpleLogEnabled))
Expand All @@ -2521,9 +2528,15 @@ public static void BoolWithDefaultWarning(

private static string BoolWithDefaultWarning(EventDefinitionBase definition, EventData payload)
{
var d = (EventDefinition<string, string>)definition;
var d = (EventDefinition<string, string, string, string, string>)definition;
var p = (PropertyEventData)payload;
return d.GenerateMessage(p.Property.Name, p.Property.DeclaringEntityType.DisplayName());
var defaultValue = p.Property.ClrType.GetDefaultValue();
return d.GenerateMessage(
p.Property.ClrType.ShortDisplayName(),
p.Property.Name,
p.Property.DeclaringEntityType.DisplayName(),
defaultValue == null ? "null" : defaultValue.ToString()!,
p.Property.ClrType.ShortDisplayName());
}

/// <summary>
Expand Down
17 changes: 11 additions & 6 deletions src/EFCore.Relational/Infrastructure/RelationalModelValidator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -675,21 +675,26 @@ protected virtual void ValidateBoolsWithDefaults(
{
foreach (var property in entityType.GetDeclaredProperties())
{
if (property.ClrType == typeof(bool)
if (!property.ClrType.IsNullableType()
&& (property.ClrType.IsEnum || property.ClrType == typeof(bool))
&& property.ValueGenerated != ValueGenerated.Never
&& property.FieldInfo?.FieldType != typeof(bool?)
&& property.FieldInfo?.FieldType.IsNullableType() != true
&& !((IConventionProperty)property).GetSentinelConfigurationSource().HasValue
&& (StoreObjectIdentifier.Create(property.DeclaringEntityType, StoreObjectType.Table) is { } table
&& (IsNotNullAndFalse(property.GetDefaultValue(table))
&& (IsNotNullAndNotDefault(property.GetDefaultValue(table))
|| property.GetDefaultValueSql(table) != null)))
{
logger.BoolWithDefaultWarning(property);
}

bool IsNotNullAndNotDefault(object? value)
=> value != null
#pragma warning disable EF1001 // Internal EF Core API usage.
&& !property.ClrType.IsDefaultValue(value);
#pragma warning restore EF1001 // Internal EF Core API usage.
}
}

static bool IsNotNullAndFalse(object? value)
=> value != null
&& (value is not bool asBool || asBool);
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,18 @@ public virtual void ProcessPropertyAnnotationChanged(
switch (name)
{
case RelationalAnnotationNames.DefaultValue:
#pragma warning disable EF1001 // Internal EF Core API usage.
if ((((IProperty)property).TryGetMemberInfo(forMaterialization: false, forSet: false, out var member, out _)
? member!.GetMemberType()
: property.ClrType)
#pragma warning restore EF1001 // Internal EF Core API usage.
== typeof(bool)
&& Equals(true, property.GetDefaultValue()))
{
propertyBuilder.HasSentinel(annotation != null ? true : null);
}

goto case RelationalAnnotationNames.DefaultValueSql;
case RelationalAnnotationNames.DefaultValueSql:
case RelationalAnnotationNames.ComputedColumnSql:
propertyBuilder.ValueGenerated(GetValueGenerated(property));
Expand Down
10 changes: 5 additions & 5 deletions src/EFCore.Relational/Properties/RelationalStrings.Designer.cs

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

58 changes: 29 additions & 29 deletions src/EFCore.Relational/Properties/RelationalStrings.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 @@ -593,8 +593,8 @@
<comment>Debug RelationalEventId.TransactionStarting string</comment>
</data>
<data name="LogBoolWithDefaultWarning" xml:space="preserve">
<value>The 'bool' property '{property}' on entity type '{entityType}' is configured with a database-generated default. This default will always be used for inserts when the property has the value 'false', since this is the CLR default for the 'bool' type. Consider using the nullable 'bool?' type instead, so that the default will only be used for inserts when the property value is 'null'.</value>
<comment>Warning RelationalEventId.BoolWithDefaultWarning string string</comment>
<value>The '{type}' property '{property}' on entity type '{entityType}' is configured with a database-generated default, but has no configured sentinel value. The database-generated default will always be used for inserts when the property has the value '{defaultValue}', since this is the CLR default for the '{type2}' type. Consider using a nullable type, using a nullable backing field, or setting the sentinel value for the property to ensure the database default is used when, and only when, appropriate. See https://aka.ms/efcore-docs-default-values for more information.</value>
<comment>Warning RelationalEventId.BoolWithDefaultWarning string string string string string</comment>
</data>
<data name="LogClosedConnection" xml:space="preserve">
<value>Closed connection to database '{database}' on server '{server}' ({elapsed}ms).</value>
Expand Down
Loading