Hello I have an entity Xs it has a 1 to 1 relationship to XEffectiveness
[Table("Xs")]
public class X : FullAuditedEntity
{
public virtual int? Effectiveness { get; set; }
[ForeignKey("Effectiveness")]
public XEffectiveness EffectiveneFk { get; set; }
}
[Table("XEffectivenesses")]
public class XEffectiveness : FullAuditedEntity
{
public virtual int XId { get; set; }
public virtual X X { get; set; }
}
When I create a new record it successfully populates both tables correctly. However when I go to update the records it fails with Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Cannot insert explicit value for identity column in table 'XEffectivenesses' when IDENTITY_INSERT is set to OFF.
My PortalDBContext.cs has the following:
modelBuilder.Entity<X>()
.HasOne(x=> x.EffectiveneFk)
.WithOne(u => u.X)
.HasForeignKey<XEffectiveness>(b => b.XId);
To workaround the issue I have enacted the following:
private async Task<int> Update(CreateOrEditXDto input)
{
var x = await _xRepository.FirstOrDefaultAsync((int)input.Id);
ObjectMapper.Map(input, x);
var TEMPeffectiveness = x.EffectiveneFk;
x.EffectiveneFk = null;
await _xRepository.UpdateAsync(x);
await _lookup_xEffectivenessRepository.InsertOrUpdateAsync(TEMPeffectiveness);
return x.Id;
}
Which essentially takes out the 1 to 1 of Effectiveness temporarily, saves the parent of the 1 to 1 which is X and then saves the Effectiveness.
I have asked also on stackoverflow and will update both if I get an answer.
1 Answer(s)
-
0
Hi @jtallon
Could you also share the code which doens't work ? Do you load XEffectiveness when loading X entity from database ?