Cannot insert explicit value for identity column in table 'xxx' when IDENTITY_INSERT is set to OF

asp.net asp.net-core c# entity-framework-core

Question

I have checked all the topics on this error with entitframework but I can't find my issue.

I use entityframework core.

I have an accomplishment and a criteriagroup in the accomplishment class.

When I save for the first time the accomplishment everything works.

Then when I want to update it I gave the error "Cannot insert explicit value for identity column in CriteriaGroups Table...

 "name": "Accomplishment1",
    "criteriaGroupId": 4,
    "categories": [],
    "criteriaGroupFk": {
        "gOperator": 0,
        "criterias": [],
        "groups": [],
        "id": 4
    },
    "id": 2
}

The class model of the accomplishment is:

[Table("Accomplishments")]
public class Accomplishment : AuditedEntity 
{

    [Required]
    public virtual string Name { get; set; }

    public virtual int? CriteriaGroupId { get; set; }

    [ForeignKey("CriteriaGroupId")]
    public CriteriaGroup CriteriaGroupFk { get; set; }

    public List<Category> Categories { get; set; }

}

The class for the criteriagroup is as below:

    [Table("CriteriaGroups")]
public class CriteriaGroup : CreationAuditedEntity 
{

    public virtual GroupOperator GOperator { get; set; }

    public List<Criteria> Criterias { get; set; }

    public List<CriteriaGroup> Groups { get; set; }
}

In my code I see that it goes to update the accomplishment object. But I think that entityframework sees the criteria group as new even if it has an id.

What's wrong with it?

I struggle since 2 days on it.

private async Task Update(CreateOrEditAccomplishmentDto input)
     {
        var accomplishment = await _accomplishmentRepository.FirstOrDefaultAsync((int)input.Id);
         ObjectMapper.Map(input, accomplishment);
         await CurrentUnitOfWork.SaveChangesAsync();
     }
1
0
10/24/2019 5:41:21 PM

Accepted Answer

Ensure to not overwrite the CriteriaGroup with an untracked object, because in this case the CriteriaGroup is considered new.

The described issue could happen if for example you don't load the related CriteriaGroupFk when loading the Accomplishment, and afterwards assigning an untracked object to CriteriaGroupFk. To resolve the issue you can use Include, e.g.:

var accomplishment = await _accomplishmentRepository.Include(x => x.CriteriaGroupFk).FirstOrDefaultAsync((int)input.Id);

See Loading Related Data and Tracking vs. No-Tracking Queries for further information.

0
10/24/2019 6:51:07 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow