You didn't provide your database table. But I assume your code is expecting the ID to be an IDENTITY field and it is not setup correctly in the database.
Cannot insert duplicate key in object 'dbo.VersionMasters'.The duplicate key value is (0). The statement has been terminated
Hi,
While I am executing the following query, I am getting error "Cannot insert duplicate key in object 'dbo.VersionMasters'.The duplicate key value is (0).
The statement has been terminated."
using (var context = new Entities())
{
var testCaseEntity = new VersionMaster()
{
TestCaseID = testCaseId,
IsDeleted = false,
SupportedVersionId = versionInfo.VersionID
};
context.VersionMasters.Add(testCaseEntity);
}
In 'VersionMasters' table, ID is primary key. Although I am not inserting ID in the above query, I am not getting why I am getting this error.
Please do let me know what I am doing wrong, Kindly waiting for your response.
Thanks,
Santosh
Developer technologies .NET Other
SQL Server Other
3 answers
Sort by: Most helpful
-
-
Erland Sommarskog 121.4K Reputation points MVP Volunteer Moderator
2022-02-08T23:00:56.107+00:00 Try running
DBCC CHECKIDENT
on the table. -
Karen Payne MVP 35,586 Reputation points Volunteer Moderator
2022-02-12T12:13:56.173+00:00 If you are still having issues, here is an example to try using LocalDb
public class VersionMaster { public int TestCaseID { get; set; } public bool IsDeleted { get; set; } }
DbContext where the key is telling EF your primary key
entity.HasKey(e => e.TestCaseID);
.public class SampleContext : DbContext { public DbSet<VersionMaster> VersionMaster { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer( @"Server=(localdb)\mssqllocaldb;" + "Database=EFSaving.ForumData;Trusted_Connection=True"); } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.ApplyConfiguration(new VersionMasterConfiguration()); } public partial class VersionMasterConfiguration : IEntityTypeConfiguration<VersionMaster> { public void Configure(EntityTypeBuilder<VersionMaster> entity) { entity.HasKey(e => e.TestCaseID); } } }
Model
public class VersionMaster { public int TestCaseID { get; set; } public bool IsDeleted { get; set; } }
Run with
using (var context = new SampleContext()) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); List<VersionMaster> list = new() { new () { IsDeleted = false }, new () { IsDeleted = false }, new () { IsDeleted = false }, }; context.AddRange(list); Console.WriteLine(context.SaveChanges()); }