Skip to content

Instantly share code, notes, and snippets.

@MichalSznajder
Last active January 29, 2021 07:52
Show Gist options
  • Select an option

  • Save MichalSznajder/10457b29538fc03da99ae7a4298917f4 to your computer and use it in GitHub Desktop.

Select an option

Save MichalSznajder/10457b29538fc03da99ae7a4298917f4 to your computer and use it in GitHub Desktop.
ValueObject as Index
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="5.0.2" />
</ItemGroup>
</Project>
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace ConsoleApp
{
public class Cinema
{
public CinemaId CinemaId { get; set; }
}
public class Show
{
public CinemaId CinemaId { get; set; }
public ShowId ShowId { get; set; }
}
public sealed record CinemaId(int Value);
public sealed record ShowId(int Value);
public class CinemaIdValueConverter : ValueConverter<CinemaId, int>
{
public CinemaIdValueConverter(ConverterMappingHints mappingHints = null)
: base(
id => id.Value,
value => new CinemaId(value),
mappingHints
) { }
}
public class ShowIdValueConverter : ValueConverter<ShowId, int>
{
public ShowIdValueConverter(ConverterMappingHints mappingHints = null)
: base(
id => id.Value,
value => new ShowId(value),
mappingHints
) { }
}
public class KinoContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseNpgsql(
"Host=localhost;Database=test;Username=postgres;Include Error Detail=true");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Cinema>(builder =>
{
builder.HasKey(e => new
{
e.CinemaId,
});
builder.Property(e => e.CinemaId)
.UseIdentityByDefaultColumn()
.HasConversion(new CinemaIdValueConverter());
});
modelBuilder.Entity<Show>(builder =>
{
builder.HasKey(e => new
{
e.CinemaId,
e.ShowId,
});
builder.Property(e => e.CinemaId)
.HasConversion(new CinemaIdValueConverter());
builder.Property(e => e.ShowId)
.HasConversion(new ShowIdValueConverter())
.ValueGeneratedNever();
});
}
}
class Program
{
static void Main(string[] args)
{
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment