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

问题描述 投票:0回答:1

我们在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();

任何帮助是极大的赞赏。

.net .net-core integration-testing asp.net-core-webapi ef-core-2.1
1个回答
3
投票

InMemory不是关系数据库。

InMemory将允许您保存违反关系数据库中的参照完整性约束的数据。

如果您想测试的行为更像真正的关系数据库,那么请考虑使用SQLite in-memory模式。

参考:InMemory is not a relational database

© www.soinside.com 2019 - 2024. All rights reserved.