we're using EF Core in our ASP.NET core API solution. There is a transactions table in the database and there is a unique index that contains two columns. So there should be no records in this table with the same values for these columns.
In our EF mapping we have this
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");
But in our integration tests where we use the in memory database provider, there will be no error raised when two identical transaction objects are added in the Transactions DbSet of the DbContext. Shouldn't this code raise an error, since we've specified that there is a unique key that includes these two columns?
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();
Any help is greatly appreciated.
A constraint has different meaning to an index. It gives the optimiser more information and allows you to have foreign keys on the column, whereas a unique index doesn't.
Configuring indexes via Data Annotations has been introduced in EF Core 5.0. By convention, an index is created in each property (or set of properties) that are used as a foreign key. EF Core only supports one index per distinct set of properties.
Right-click the table on which you want to create a unique index and select Design. On the Table Designer menu, select Indexes/Keys. In the Indexes/Keys dialog box, click Add. Select the new index in the Selected Primary/Unique Key or Index text box.
In the DbContext OnModelCreating you add the default value. The 'bool' property 'Active' on entity type 'Foundation' is configured with a database-generated default. This default will always be used for inserts when the property has the value 'false', since this is the CLR default for the 'bool' type.
InMemory
is not a relational database.
InMemory will allow you to save data that would violate referential integrity constraints in a relational database.
If you want to test against something that behaves more like a true relational database, then consider using SQLite in-memory mode.
Reference: InMemory is not a relational database
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With