{"record":{"id":"ab2ca9c4601d50aa","repo":"dotnet/efcore","slug":"the-literal-expression-expression-for-type","errorCode":null,"errorMessage":"The literal expression '{expression}' for '{type}' cannot be parsed. Only simple constructor calls and factory methods are supported.","messagePattern":"The literal expression '(.+?)' for '(.+?)' cannot be parsed\\. Only simple constructor calls and factory methods are supported\\.","errorType":"exception","errorClass":"NotSupportedException","httpStatus":null,"severity":"error","filePath":"src/EFCore.Design/Design/Internal/CSharpHelper.cs","lineNumber":1107,"sourceCode":"            var genericArguments = valueType.GetGenericArguments();\n            switch (value)\n            {\n                case IList list when genericArguments.Length == 1 && valueType.GetGenericTypeDefinition() == typeof(List<>):\n                    return List(genericArguments[0], list);\n                case IDictionary dict when genericArguments.Length == 2 && valueType.GetGenericTypeDefinition() == typeof(Dictionary<,>):\n                    return Dictionary(genericArguments[0], genericArguments[1], dict);\n            }\n        }\n\n        var mapping = _typeMappingSource.FindMapping(literalType);\n        if (mapping != null)\n        {\n            var builder = new StringBuilder();\n            var expression = mapping.GenerateCodeLiteral(value);\n            var handled = HandleExpression(expression, builder);\n\n            return !handled\n                ? throw new NotSupportedException(\n                    DesignStrings.LiteralExpressionNotSupported(\n                        expression.ToString(),\n                        literalType.ShortDisplayName()))\n                : builder.ToString();\n        }\n\n        throw new InvalidOperationException(DesignStrings.UnknownLiteral(literalType));\n    }\n\n    private bool HandleExpression(Expression expression, StringBuilder builder, bool simple = false)\n    {\n        // Only handle trivially simple cases for `new` and factory methods\n        switch (expression.NodeType)\n        {\n            case ExpressionType.NewArrayInit:\n                builder\n                    .Append(\"new \")\n                    .Append(Reference(expression.Type.GetElementType()!))","sourceCodeStart":1089,"sourceCodeEnd":1125,"githubUrl":"https://github.com/dotnet/efcore/blob/3a2006ef569de08368d59db5e1468aa8f407e4f8/src/EFCore.Design/Design/Internal/CSharpHelper.cs#L1089-L1125","documentation":"Thrown by CSharpHelper while scaffolding a design-time literal: the type mapping's GenerateCodeLiteral returned an expression tree whose shape the helper cannot render (it only understands simple constructor calls and static factory methods). This is a NotSupportedException raised during code generation for migrations/seeds or compiled-model literals.","triggerScenarios":"A value of a custom or third-party type is used as a model constant/default (HasDefaultValue, seed data, discriminator) and its CoreTypeMapping.GenerateCodeLiteral emits something other than NewExpression, factory MethodCallExpression, or a supported primitive expression. Nested complex expressions orMemberInit fall through HandleExpression and return false.","commonSituations":"Custom value converters whose target type has no code-literal support; NodaTime or other provider types used as column defaults; upgrading EF Core and a previously-supported literal shape is now rejected.","solutions":["Implement CoreTypeMapping.GenerateCodeLiteral on the custom type mapping to return a NewExpression or a static factory MethodCallExpression.","If the literal is a default/discriminator/seed, replace the complex value with a primitive the scaffolder understands (string, int, GUID).","Move the constant out of the model and apply it at runtime instead of via HasDefaultValue.","Report the type to the provider author so GenerateCodeLiteral is supported upstream."],"exampleFix":"// before - custom struct used as a default value produces an unmappable literal\nmodelBuilder.Entity<Foo>().Property(x => x.Custom).HasDefaultValue(CustomValue.Parse(\"abc\"));\n\n// after - generate a supported factory-method literal\npublic sealed class CustomValue\n{\n    public static Expression GenerateCodeLiteral(object v)\n        => Expression.Call(typeof(CustomValue).GetMethod(nameof(Parse))!,\n                           Expression.Constant(((CustomValue)v).Raw));\n}","handlingStrategy":"validation","validationCode":"var mapping = typeMappingSource.FindMapping(typeof(CustomValue));\nif (mapping?.GenerateCodeLiteral(sample) is Expression e\n    && !IsSimpleCtorOrFactory(e))\n{\n    throw new InvalidOperationException(\n        \"CustomValue literal cannot be scaffolded; implement GenerateCodeLiteral.\");\n}","typeGuard":"static bool IsSimpleCtorOrFactory(Expression e)\n    => e is NewExpression or MethodCallExpression { Object: null };\n","tryCatchPattern":"try { helper.UnknownLiteral(value); }\ncatch (NotSupportedException ex) when (ex.Message.Contains(\"cannot be parsed\"))\n{ /* fall back to a primitive constant or compute at runtime */ }","preventionTips":["Implement CoreTypeMapping.GenerateCodeLiteral for any custom mapped type used as a model constant.","Avoid non-primitive defaults in the model; apply them in code.","Run scaffolding in CI to catch literal-generation regressions early."],"tags":["scaffolding","design-time","type-mapping","literal"],"backgroundTag":null,"analyzedSha":"3a2006ef569de08368d59db5e1468aa8f407e4f8","analyzedAt":"2026-08-11T23:42:04.146Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}