{"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/dbf9771522148d61a2467854921bd5dc6f6e6916/src/EFCore.Relational/Extensions/RelationalPropertyExtensions.cs#L1052-L1088","documentation":"SetDefaultValue converts the supplied value to the property's CLR type via ConvertDefaultValue (RelationalPropertyExtensions.cs:1070, RelationalStrings.IncorrectDefaultValueType). If the value's type is not assignable to the property's CLR type (after UnwrapNullableType) AND Convert.ChangeType fails, EF throws, naming the value, its type, the property, and the expected CLR type.","triggerScenarios":"Passing a value whose type cannot become the property's CLR type, e.g. SetDefaultValue(\"abc\") on an int column, SetDefaultValue(42) on a Guid, SetDefaultValue(DateTime.Now) on a DateTimeOffset without explicit cast, SetDefaultValue(someEnum) where an int is expected.","commonSituations":"Config-driven default values read from JSON/string config without conversion; copying defaults across properties of differing types in a loop; passing a boxed wrong type.","solutions":["Pass a value of a type assignable to property.ClrType (after unwrapping Nullable<T>).","Convert explicitly before calling: SetDefaultValue(Convert.ChangeType(raw, property.ClrType)).","Use the typed overload or supply DBNull.Value for SQL NULL, or null for 'no default'.","For enums, pass the underlying int or a value of the enum type matching the property."],"exampleFix":"// before\nmodelBuilder.Entity<Order>()\n    .Property(o => o.CreatedAt)            // DateTimeOffset\n    .HasDefaultValue(DateTime.Now);        // DateTime -> throws\n\n// after\nmodelBuilder.Entity<Order>()\n    .Property(o => o.CreatedAt)\n    .HasDefaultValue(DateTimeOffset.Now);  // matching CLR type","handlingStrategy":"type-guard","validationCode":"object defaultValue = /* from config */;\nvar clrType = property.ClrType.UnwrapNullableType();\nif (defaultValue != null && !clrType.IsAssignableFrom(defaultValue.GetType()))\n{\n    defaultValue = Convert.ChangeType(defaultValue, clrType, CultureInfo.InvariantCulture);\n}\nproperty.SetDefaultValue(defaultValue);","typeGuard":"static bool DefaultValueAssignable(IReadOnlyProperty p, object? value)\n    => value is null || value == DBNull.Value\n       || p.ClrType.UnwrapNullableType().IsAssignableFrom(value.GetType());","tryCatchPattern":null,"preventionTips":["Always pass a value whose runtime type matches property.ClrType (unwrapped of Nullable<T>).","For config-driven defaults, Convert.ChangeType to the property CLR type first.","Use DBNull.Value to mean SQL NULL, null to clear the default.","Beware enum defaults: pass the enum type or its underlying integral type."],"tags":["default-value","type-mismatch","model-building","property-mapping"],"analyzedSha":"dbf9771522148d61a2467854921bd5dc6f6e6916","analyzedAt":"2026-08-06T20:46:03.226Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}