dotnet core 2.2 EntityFramework with postgres

.net-core c# entity-framework-core

Question

I followed the documentation on Postgres C# website.

When I run this code I get:

The entity type 'Bar' requires a primary key to be defined.

POCOs:

public class Foo
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public string Name { get; set; }

    [Column(TypeName = "jsonb")]
    public Bar Bar { get; set; }
}

public class Bar
{
    public string Prop1 { get; set; }

    public string Prop2 { get; set; }
}

My goal is to avoid using string as a property type of Bar and let the entity framework handle JSON serialize, deserialize. I don't want the Bar to be a separate table. I want it to be a JSON column on Foo.

1
3
9/26/2019 7:27:35 PM

Accepted Answer

After upgrading to .NET Core 3.0 from 2.2 everything worked fine. The following is the new csproj:

<Project Sdk="Microsoft.NET.Sdk.Web">
    <PropertyGroup>
        <TargetFramework>netcoreapp3.0</TargetFramework>
        <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
        <AssemblyName>App</AssemblyName>
        <RootNamespace>App</RootNamespace>
    </PropertyGroup>

    <ItemGroup>
        <PackageReference Include="Microsoft.AspNetCore.App" />
        <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.0.0" />
        <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="3.0.0" />
    </ItemGroup>
</Project>
0
9/27/2019 7:17:55 PM

Popular Answer

You need to create ValueConverter<Bar, string> or use function expressions directly in HasConversion in on OnModelCreating.

Example:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Foo>()
        .Property(x => x.Bar)
        .HasConversion(
        v => JsonConvert.SerializeObject(v),
        v => JsonConvert.DeserializeObject<Bar>(v));                

    base.OnModelCreating(modelBuilder);
}

Reference: https://docs.microsoft.com/en-us/ef/core/modeling/value-conversions



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow