I have a GamingLimit
class with a composite key that uses the properties PersonalNationalIdHash
and Timeframe
as composite key.
// GamingLimit.cs
public class GamingLimit
{
public string? PlayerNationalIdHash { get; set; }
public decimal Limit { get; set; }
public string? Currency { get; set; }
public GamingLimitTimeframe Timeframe { get; set; }
}
// GamingLimitTimeframe.cs
public enum GamingLimitTimeframe
{
All,
Daily,
Weekly,
Monthly,
Quarterly,
Yearly
}
I set up EF Core to use the mentioned properties as a composite key with the OnModelCreating
override with dbContext
:
// ApplicationDbContext.cs
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<GamingLimit>()
.HasKey(nameof(GamingLimit.PlayerNationalIdHash),
nameof(GamingLimit.Timeframe));
}
I seed the database like so
// SeedDb.cs
public static void InitializeDbForTests(ApplicationDbContext db)
{
var gamingLimitSeedData = new List<GamingLimit>
{
new()
{
PlayerNationalIdHash = "1",
Limit = 2500m,
Currency = "SHILLINGS",
Timeframe = GamingLimitTimeframe.Monthly,
},
new()
{
PlayerNationalIdHash = "1",
Limit = 500m,
Currency = "SHILLINGS",
Timeframe = GamingLimitTimeframe.Daily,
}
};
gamingLimitSeedData.ForEach(x => db.GamingLimits?.Add(x));
db.SaveChanges();
}
Whenever I have more than one entity going into the context I get the error:
The instance of entity type 'GamingLimit' cannot be tracked because another instance with the same key value for {'TempId'} is already being tracked
This happens at the line
gamingLimitSeedData.ForEach(x => db.GamingLimits?.Add(x));
I have no idea why, since all the other answers I have seen don't have this specific issue.
I have tried to to add an integer field with the name Id like so
// GamingLimit.cs
public class GamingLimit
{
public int Id { get; set; }
public string? PlayerNationalIdHash { get; set; }
public decimal Limit { get; set; }
public string? Currency { get; set; }
public GamingLimitTimeframe Timeframe { get; set; }
}
while keeping the OnModelCreating
override with the composite key.
I am using Postgres 9.6
Any idea what could be the issue?