Microsoft Technologies based on the .NET software framework. Miscellaneous topics that do not fit into specific categories.
Try running DBCC CHECKIDENT on the table.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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
Microsoft Technologies based on the .NET software framework. Miscellaneous topics that do not fit into specific categories.
Additional SQL Server features and topics not covered by specific categories
Try running DBCC CHECKIDENT on the table.
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.
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());
}