Created
February 7, 2024 18:20
-
-
Save JustusGreiberORGADATA/4f4529c282cc0abd379bb3871c11063d to your computer and use it in GitHub Desktop.
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 Microsoft.Data.Sqlite; | |
using Microsoft.EntityFrameworkCore; | |
using var connection = new SqliteConnection("DataSource=:memory:"); | |
connection.Open(); | |
var options = new DbContextOptionsBuilder<TestContext>() | |
.UseSqlite(connection) | |
.LogTo(Console.WriteLine) | |
.EnableSensitiveDataLogging().Options; | |
try | |
{ | |
using (TestContext testContext = new(options)) | |
{ | |
await testContext.Database.EnsureCreatedAsync(); | |
} | |
using (TestContext testContext = new(options)) | |
{ | |
testContext.TestEntities.Add(new TestEntity { Id = 1, UserId = 1, IsPrimary = false }); | |
testContext.TestEntities.Add(new TestEntity { Id = 2, UserId = 1, IsPrimary = true }); | |
await testContext.SaveChangesAsync(); | |
} | |
using (TestContext testContext = new(options)) | |
{ | |
TestEntity test1 = await testContext.TestEntities.SingleAsync(t => t.Id == 1); | |
TestEntity test2 = await testContext.TestEntities.SingleAsync(t => t.Id == 2); | |
test1.IsPrimary = true; | |
test2.IsPrimary = false; | |
await testContext.SaveChangesAsync(); | |
} | |
} | |
catch (Exception ex) | |
{ | |
// Does not throw in EF Core 6. Throws in EF Core 7 and 8. | |
throw; | |
} | |
public class TestContext : DbContext | |
{ | |
public DbSet<TestEntity> TestEntities { get; set; } | |
public TestContext(DbContextOptions<TestContext> options) : base(options) | |
{ | |
} | |
protected override void OnModelCreating(ModelBuilder modelBuilder) | |
{ | |
base.OnModelCreating(modelBuilder); | |
modelBuilder.Entity<TestEntity>() | |
.HasIndex(e => new { e.UserId, e.IsPrimaryNormalized }) | |
.IsUnique(); | |
modelBuilder.Entity<TestEntity>() | |
.Property(e => e.IsPrimaryNormalized) | |
.HasComputedColumnSql($"IIF(IsPrimary, true, null)", stored: true); | |
} | |
} | |
public class TestEntity | |
{ | |
public int Id { get; set; } | |
public int UserId { get; set; } | |
public bool IsPrimary { get; set; } | |
public bool? IsPrimaryNormalized { get => IsPrimary ? true : null; set { } } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment