{"record":{"id":"9bc784e63c6abaa6","repo":"dotnet/efcore","slug":"default-value-value-of-type-valuetype-cann","errorCode":null,"errorMessage":"Default value '{value}' of type '{valueType}' cannot be set on property '{property}' of type '{propertyType}' in entity type '{entityType}'.","messagePattern":"Default value '(.+?)' of type '(.+?)' cannot be set on property '(.+?)' of type '(.+?)' in entity type '(.+?)'\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/EFCore.Relational/Extensions/RelationalPropertyExtensions.cs","lineNumber":1070,"sourceCode":"\n    private static object? ConvertDefaultValue(IReadOnlyProperty property, object? value)\n    {\n        if (value == null\n            || value == DBNull.Value)\n        {\n            return value;\n        }\n\n        var valueType = value.GetType();\n        if (!property.ClrType.UnwrapNullableType().IsAssignableFrom(valueType))\n        {\n            try\n            {\n                return Convert.ChangeType(value, property.ClrType, CultureInfo.InvariantCulture);\n            }\n            catch\n            {\n                throw new InvalidOperationException(\n                    RelationalStrings.IncorrectDefaultValueType(\n                        value, valueType.ShortDisplayName(), property.Name, property.ClrType, property.DeclaringType.DisplayName()));\n            }\n        }\n\n        return value;\n    }\n\n    /// <summary>\n    ///     Gets the <see cref=\"ConfigurationSource\" /> for the default value.\n    /// </summary>\n    /// <param name=\"property\">The property.</param>\n    /// <returns>The <see cref=\"ConfigurationSource\" /> for the default value.</returns>\n    public static ConfigurationSource? GetDefaultValueConfigurationSource(this IConventionProperty property)\n        => property.FindAnnotation(RelationalAnnotationNames.DefaultValue)?.GetConfigurationSource();\n\n    /// <summary>\n    ///     Gets the maximum length of data that is allowed in this property. For example, if the property is a <see cref=\"string\" />","sourceCodeStart":1052,"sourceCodeEnd":1088,"githubUrl":"https://github.com/dotnet/efcore/blob/3a2006ef569de08368d59db5e1468aa8f407e4f8/src/EFCore.Relational/Extensions/RelationalPropertyExtensions.cs#L1052-L1088","documentation":"When setting a default value on a property, EF Core checks that the value's runtime type is assignable to the property's ClrType. If not, it attempts Convert.ChangeType as a fallback; if that also throws, EF Core reports the mismatch with the value, its type, the property name, the expected ClrType, and the declaring entity type.","triggerScenarios":"Calling property.SetDefaultValue(value) / HasDefaultValue(value) where value's type is neither assignable to the property's ClrType nor convertible via Convert.ChangeType (e.g. a string default on an int column that is not numeric, or a complex object on a scalar column).","commonSituations":"Passing a boxed value of the wrong type (e.g. \"abc\" for an int column); using enums with mismatched underlying types; timezone/DateTimeOffset mismatches; config generated from external metadata with inconsistent types.","solutions":["Supply a default value whose runtime type matches (or is convertible to) the property's ClrType.","For enums, pass the enum's underlying numeric value or the strongly-typed enum value.","Pre-convert the value with Convert.ChangeType before calling SetDefaultValue.","If you need a SQL-side default expression instead, use HasDefaultValueSql."],"exampleFix":"// before\nmodelBuilder.Entity<User>().Property(u => u.Age).HasDefaultValue(\"twenty-one\");\n// after\nmodelBuilder.Entity<User>().Property(u => u.Age).HasDefaultValue(21);","handlingStrategy":"type-guard","validationCode":"// Validate the default value type before assigning.\nvar expected = property.ClrType.UnwrapNullableType();\nvar actual = value.GetType();\nif (!expected.IsAssignableFrom(actual)\n    && !(expected.IsEnum && expected.GetEnumUnderlyingType() == actual)\n    && !IsConvertible(actual, expected))\n{\n    throw new InvalidOperationException($\"Default value type {actual} is not compatible with {expected}.\");\nproperty.SetDefaultValue(value);\n\nstatic bool IsConvertible(Type from, Type to)\n    => TypeDescriptor.GetConverter(from).CanConvertTo(to);","typeGuard":"static bool IsCompatibleDefaultValue(Type clrType, object? value)\n    => value is null\n       || clrType.UnwrapNullableType().IsAssignableFrom(value.GetType())\n       || (clrType.UnwrapNullableType().IsEnum\n           && clrType.UnwrapNullableType().GetEnumUnderlyingType() == value.GetType());","tryCatchPattern":null,"preventionTips":["Always pass a strongly-typed value matching the property's ClrType.","For enums, pass the enum value, not a string, unless convertible.","Use HasDefaultValueSql for non-convertible defaults.","Add a model test asserting every HasDefaultValue value type-checks."],"tags":["default-value","type-mismatch","property","model-builder","configuration"],"backgroundTag":null,"analyzedSha":"3a2006ef569de08368d59db5e1468aa8f407e4f8","analyzedAt":"2026-08-11T23:42:04.146Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}