Search code examples
c#jsonentity-framework-core

EF Core 7 Json column with different column name


We are trying to migrate from the HasConversion option to map ef core properties to .net types which are actually json columns in the database, to the native support for Json columns in ef core 7.

So we used to have something like:

builder.Property(x => x.Definition).HasConversion(x => x.ToJSON(), x => x.ToObject<ViewDefinition>());

and now we are doing:

builder.OwnsOne(x => x.Definition, nb =>
{
    nb.ToJson();
}

however, in our case, the Definition isn't called Definition in the database, but is called ViewDefinition. However, we need the property in the ef entity to be called ViewDefinition. Now it seems that the OwnsOne setup ignores the [Column("ViewDefinition")] attribute on the property, and I can also not find any way to set the name of the property in the builder.

Now my question is, what can I do in my ef configuration to make sure the Definition property maps to the ViewDefinition column in sql server?


Solution

  • You are correct that [Column("ViewDefinition")] isn´t currently picked up for ToJson() mapped properties.

    Instead, you should use the ToJson builder extension to specify the alternate name as shown below;

    builder
        .Property(
            entity => entity.Definition,
            builder => builder.ToJson("ViewDefinition"));
    

    fyi efcore 7.0.8