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

Posted

技术标签:

【中文标题】在 EF Core 映射上添加唯一索引似乎不起作用【英文标题】:Adding a unique index on EF Core mapping does not seem to work 【发布时间】:2019-02-14 23:51:06 【问题描述】:

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

非常感谢任何帮助。

【问题讨论】:

【参考方案1】:

InMemory 不是关系数据库。

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

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

参考:InMemory is not a relational database

【讨论】:

以上是关于在 EF Core 映射上添加唯一索引似乎不起作用的主要内容,如果未能解决你的问题,请参考以下文章