Ok, first off I have seen several questions on this issue. I have gone through just about all of them and none of the solutions prescribed worked for me. I am using asp.net core 1.1.0 and SQL Server 2016. I am also using the code first approach. The following is my mappings for the table in question
public class TierMap : IEntityTypeConfiguration<Tier>
{
public void Map(EntityTypeBuilder<Tier> builder)
{
builder.HasKey(a => a.TierID);
builder.Property(a => a.TierID).UseSqlServerIdentityColumn<int>();
builder.HasOne(a => a.Country)
.WithMany(a => a.Tiers)
.HasForeignKey(a => a.CountryID);
}
}
Below is the design view of the table in SQL Server:
When I create a new instance of a Tier object, all the properties except the TierID get some value (a random negative integer). So inserting into the database throws the following error
Cannot insert explicit value for identity column in table 'Tiers' when IDENTITY_INSERT is set to OFF.
Below is the code the attempts to save the data
[HttpPost("AddTier")]
public async Task<IActionResult> AddTier([FromBody]TierDataModel model)
{
if (!ModelState.IsValid)
{
Response.AddApplicationError("Data is invalid ");
return BadRequest();
}
Tier tier = new Tier();
tier.TierName = model.TierName;
tier.TierNo = model.TierNo;
tier.CountryID = model.CountryID;
_tierService.AddTier(tier);
await _unitOfWorkAsync.SaveChangesAsync();
return Ok();
}
