Skip to content

Set MaxLength ToJson column #29823

Closed as not planned
Closed as not planned
@totpero

Description

@totpero

Hi,

I update my code from ef6 to ef7.
In my ef6 code I map my JSON column using custom Conversion method.
Now I want to use the new ef7 feature ToJson but I encountered a problem,

My EF6 configuration was:

builder.Property(q => q.MyJsonColumn)
	.HasMaxLength(500)
        .HasDefaultValueSql("'{}'")
	.HasJsonConversion();

Now my EF7 configuration is:

builder.Property(q => q.MyJsonColumn)
	.HasMaxLength(500)
        .HasDefaultValueSql("'{}'");
builder.OwnsOne(x => x.MyJsonColumn).ToJson(nameof(MyEntity.MyJsonColumn))

If I set ToJson configuration after the property configuration, I get this error:

InvalidOperationException: The property or navigation 'MyJsonColumn' cannot be added to the entity type 'MyEntity' because a property or navigation with the same name already exists on entity type 'MyEntity'.

Microsoft.EntityFrameworkCore.Metadata.Internal.EntityType.AddNavigation(MemberIdentity navigationMember, ForeignKey foreignKey, bool pointsToPrincipal)

If I set ToJson configuration before the property configuration like this:

builder.OwnsOne(x => x.MyJsonColumn).ToJson(nameof(MyEntity.MyJsonColumn))
builder.Property(q => q.MyJsonColumn)
	.HasMaxLength(500)
        .HasDefaultValueSql("'{}'");

I get this error:

InvalidOperationException: 'MyJsonColumn' cannot be used as a property on entity type 'MyEntity' because it is configured as a navigation.

Microsoft.EntityFrameworkCore.Metadata.Internal.InternalEntityTypeBuilder.Property(Type propertyType, string propertyName, MemberInfo memberInfo, Nullable<ConfigurationSource> typeConfigurationSource, Nullable<ConfigurationSource> configurationSource)

I search in your tests here and here but I didn't find anything.

I use IEntityTypeConfiguration for my entities configurations.

My question is:

How can I configure HasMaxLength or HasDefaultValueSql or other property configuration to my Entity column?


EF Core version: 7.0.0
Database provider: (e.g. Microsoft.EntityFrameworkCore.SqlServer)
Target framework: (e.g. .NET 7.0)
Operating system: Win 11
IDE: Visual Studio 2022 17.4.2

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions