Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ToJson when using IEntityTypeConfiguration<T> to configure entities

I am following the announcement here to convert some of my entities to be stored as JSON in my SQL server. I can see in the blog post how this can be done in the OnModelCreating method, but how exactly do we do this when using IEntityTypeConfiguration to configure the tables and properties?

I have a configuration class for my entity, implementing IEntityTypeConfiguration. I override the Configure method in there to configure the entity. I'd like one of the navigation properties of my entity to be stored as JSON in the same table instead of a separate table.

Appreciate any pointers.

like image 631
Snooks Avatar asked Oct 29 '25 19:10

Snooks


1 Answers

The same way as you would do via ModelBuilder (apart from skipping the Entity call, based on What's New example):

class AuthorCfg : IEntityTypeConfiguration<Author>
{
    public void Configure(EntityTypeBuilder<Author> builder)
    {
        builder.OwnsOne(
            author => author.Contact, 
            ownedNavigationBuilder =>
            {
                ownedNavigationBuilder.ToJson();
                ownedNavigationBuilder.OwnsOne(contactDetails => contactDetails.Address);
            });
    }
}

Note that RelationalOwnedNavigationBuilderExtensions.ToJson is part of Microsoft.EntityFrameworkCore.Relational package so be sure that the project holding the configurations has it installed.

like image 80
Guru Stron Avatar answered Oct 31 '25 08:10

Guru Stron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!