Innofactor / EfCoreJsonValueConverter

JSON ValueConverter for EF Core 3.0+
GNU Lesser General Public License v3.0
96 stars 17 forks source link

Do not require defining JSON properties with Property #2

Closed jukkahyv closed 5 years ago

jukkahyv commented 6 years ago

Problem is that without the call to Property(), EF recognizes JSON fields as navigation properties instead of plain properties and tries to look for a primary key.

System.InvalidOperationException: The entity type 'Address' requires a primary key to be defined.

For now, I cannot find a way to remove the navigation property from the entity type.

Related to https://github.com/aspnet/EntityFrameworkCore/issues/11199

WillFvrther commented 6 years ago

Add the following code before the builder.AddJsonFields() call to do the trick.

foreach (var entity in builder.Model.GetEntityTypes())
{
    foreach (var property in entity.ClrType.GetProperties())
    {
        if (property.CustomAttributes.Any(a => a.AttributeType == typeof(JsonFieldAttribute)))
        {
            builder.Entity(entity.ClrType).Property(property.PropertyType, property.Name);
        }
    }
}

This will force all entities clr properties to be seen as an entity property instead of a navigation. It could be added in the AddJsonFields call.