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

EF Core 6 Dictionary<string, object> map to jsonb #2134

Closed
ColinZeb opened this issue Dec 2, 2021 · 3 comments
Closed

EF Core 6 Dictionary<string, object> map to jsonb #2134

ColinZeb opened this issue Dec 2, 2021 · 3 comments

Comments

@ColinZeb
Copy link

ColinZeb commented Dec 2, 2021

this code in EF Core 5 work correct.

 /// <summary>
/// Extension Data
/// </summary>
[Comment("Extension Data")]
[JsonExtensionData]
[Column(TypeName = "jsonb")]
public Dictionary<string, object> ExtensionData { get; set; }

and in ef core 6.0.throw a error

The navigation 'Attachment.ExtensionData' must be configured in 'OnModelCreating' with an explicit name for the target shared-type entity type, or excluded by calling 'EntityTypeBuilder.Ignore'.

@ColinZeb
Copy link
Author

ColinZeb commented Dec 6, 2021

Similar issue

      public int? GroupId { get; set; }
      [Column(TypeName = "jsonb")]
      public DataDictionary Group { get; set; }

Group is a table and entity.
This code will be recognized by EF as a foreign key relationship.
I need EF to recognize jsonb in preference to foreign keys
Or is there a way to cancel the foreign key and navigation property.

@roji
Copy link
Member

roji commented Dec 6, 2021

This is a problem in EF Core itself - Dictionary<string, object> is specially recognized as a property bag. I've opened dotnet/efcore#26903 to track this there, in the meantime you should be able to work around this by specifying:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<...>().Property(b => b.ExtensionData).Metadata.SetProviderClrType(null);
}

Note that Dictionary<string,string> is fine (or anything else that isn't specifically Dictionary<string,object>. You can also map to your own POCO, or to JsonDocument (see the docs).

@roji roji closed this as completed Dec 6, 2021
@ColinZeb
Copy link
Author

ColinZeb commented Dec 7, 2021

to resolve this problem in once code.
i write this code:

foreach (var item in modelBuilder.Model.GetEntityTypes())
{
    foreach (var p in item.ClrType.GetProperties())
    {
        if (p.GetCustomAttribute<ColumnAttribute>()?.TypeName == "jsonb")
        {
            modelBuilder.Entity(item.ClrType).Property(p.Name).Metadata.SetProviderClrType(null);
        }
    }
}

@roji

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants