在 EF Core 映射上添加唯一索引似乎不起作用

Adding a unique index on EF Core mapping does not seem to work

我们在 ASP.NET 核心 API 解决方案中使用 EF Core。数据库中有一个事务 table 并且有一个包含两列的唯一索引。因此,此 table 中不应有这些列具有相同值的记录。

在我们的 EF 映射中,我们有这个

        builder.HasIndex(e => new { e.RsaSessionId, e.SessionId }).IsUnique(true).HasName("IX_Transactions");

        builder.Property(e => e.RsaSessionId)
            .HasColumnName(nameof(Transaction.RsaSessionId))
            .IsRequired();

        builder.Property(e => e.SessionId)
            .HasColumnName(nameof(Transaction.SessionId))
            .IsRequired()
            .HasColumnType("uniqueidentifier");

但是在我们使用内存数据库提供程序的集成测试中,当在 DbContext 的 Transactions DbSet 中添加两个相同的事务对象时,不会引发错误。这段代码不应该引发错误,因为我们已经指定有一个包含这两列的唯一键吗?

var rsaSessionID=1;
Guid issuerSessionId=Guid.NewGuid();

//create two transactions with the same values for the two fields in the unique index
    var transaction = new Transaction(rsaSessionID, issuerSessionId, ... other fields ... );
    var transaction = new Transaction(rsaSessionID, issuerSessionId, ... other fields ... );
    this.fixture.Context.Transactions.Add(transaction);
this.fixture.Context.Transactions.Add(transaction2);
this.fixture.Context.SaveChanges();

非常感谢任何帮助。

InMemory 不是关系数据库。

InMemory will allow you to save data that would violate referential integrity constraints in a relational database.

如果您想针对更像真正关系数据库的东西进行测试,请考虑使用 SQLite in-memory 模式。

参考:InMemory is not a relational database