Created
March 14, 2021 11:23
-
-
Save abdusco/b7d1482a8b929d1b99c2406ae209c3ce to your computer and use it in GitHub Desktop.
EF Core use custom Guid generator for ids
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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