Dot-Net

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

  • September 11, 2018

我們在我們的 ASP.NET 核心 API 解決方案中使用 EF Core。數據庫中有一個事務表,並且有一個包含兩列的唯一索引。因此,此表中不應該有這些列具有相同值的記錄。

在我們的 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 將允許您在關係數據庫中保存違反參照完整性約束的數據。

如果您想針對行為更像真正的關係數據庫的東西進行測試,請考慮使用SQLite 記憶體模式。

參考:InMemory 不是關係型數據庫

引用自:https://stackoverflow.com/questions/52259580