Skip to content

Instantly share code, notes, and snippets.

@abdusco
Created March 14, 2021 11:23
Show Gist options
  • Save abdusco/b7d1482a8b929d1b99c2406ae209c3ce to your computer and use it in GitHub Desktop.
Save abdusco/b7d1482a8b929d1b99c2406ae209c3ce to your computer and use it in GitHub Desktop.
EF Core use custom Guid generator for ids
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="5.0.4" />
<PackageReference Include="NewId" Version="3.0.3" />
</ItemGroup>
</Project>
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using MassTransit;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.ValueGeneration;
namespace EfCustomIdGenerator
{
class Program
{
static void Main(string[] args)
{
var db = new DemoDbContext();
db.Database.OpenConnection();
db.Database.EnsureCreated();
var user = new User { Name = "abdus" };
Console.WriteLine(user);
Console.WriteLine(db.Entry(user).State);
db.Add(user);
Console.WriteLine(db.Entry(user).State);
db.SaveChanges();
user = db.Users.First();
Console.WriteLine(user);
Console.WriteLine(db.Entry(user).State);
user.Name = "abdus!";
Console.WriteLine(db.Entry(user).State);
db.SaveChanges();
Console.WriteLine(user);
}
}
record User
{
public string Id { get; set; }
public string Name { get; set; }
}
class DemoDbContext : DbContext
{
public DbSet<User> Users { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Data Source=:memory:");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>(entity =>
{
entity.Property(e => e.Id).HasValueGenerator<SequentialGuidGenerator>();
});
}
}
class SequentialGuidGenerator : ValueGenerator
{
public override bool GeneratesTemporaryValues => false;
protected override object NextValue([NotNullAttribute] EntityEntry entry) => NewId.NextGuid().ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment