'The instance of entity type cannot be tracked because another instance with the key value is already being tracked
I'm trying to update my model calling Update from my controller but I'm getting the error:
The instance of entity type 'SearchFilter' cannot be tracked because another instance with the key value '{SearchFilterId: -1}' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.
I even tried calling the 2nd Update method at the end and all the things that are commented out, but didn't work. These are my update functions and also the mapping done with the Search children SearchSources and SearchFilters (convert from DTO model to entity)
public async Task Update(SearchInput search)
{
var entry = _context.Searches
.FirstOrDefault(item => item.Name == search.Name);
if (entry != null)
{
entry.Name = search.Name;
entry.CreatedByUserId = search.CreatedByUserId;
entry.ProjectId = search.ProjectId;
entry.GlobalSearchText = search.GlobalSearchText;
entry.SearchSources = new List<SearchSource>();
entry.SearchFilters = new List<SearchFilter>();
entry.SearchSources = search.SearchSources.Select(y => ManualMapper.ConvertSearchSourceDTOToSearchSourceEntity(y)).ToList();
entry.SearchFilters = search.SearchFilters.Select(s => ManualMapper.ConvertSearchFilterDTOEntityToSearchFilterEntity(s)).ToList();
//Update(entry);
await _context.SaveChangesAsync();
}
}
public void Update(Search entity)
{
var model = _context.Entry(entity);
model.State = EntityState.Modified;
_context.SaveChanges();
}
public static Entities.SearchSource? ConvertSearchSourceDTOToSearchSourceEntity(DTO.SearchSourceDTO? entity)
{
return entity == null ? null : new Entities.SearchSource
{
DataSourceId = entity.DataSourceId,
Name = entity.Name,
SearchId = entity.SearchId,
ShowActive = entity.ShowActive
};
}
public static Entities.SearchFilter? ConvertSearchFilterDTOEntityToSearchFilterEntity(DTO.SearchFilterDTO entity)
{
return entity == null ? null : new Entities.SearchFilter
{
SearchId = entity.SearchId,
SearchFilterId = entity.SearchFilterId,
GroupNum = entity.GroupNum,
Logic = entity.Logic,
OperatorId = entity.OperatorId,
Value = entity.Value,
VariableId = entity.VariableId,
CategoryId = entity.CategoryId,
CategoryTypeId = entity.CategoryTypeId,
Order = entity.Order
};
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
