我有这样的模型:
public class Parent
{
public ChildA ChildA { get; set;}
public ChildB ChildB { get; set;}
}
在我的缓存中,我存储这些对象的集合以供统计。当我尝试保存此集合时,我收到无法添加 ChildA 的错误,因为它违反了主键约束。
ICollection<Metric> statistics = this.cacheService.Get<ICollection<Metric>>(statisticsCacheKey);
if (statistics.Any())
{
foreach (Parent parent in statistics)
{
this.dataService.Attach<ChildA>(parent.ChildA);
this.dataService.Attach<ChildB>(parent.ChildB);
this.parentRepository.Create(parent);
}
await this.dataService.SaveChangesAsync();
statistics.Clear();
this.cacheService.Put<ICollection<Parent>>(statisticsCacheKey, statistics);
}
ChildA 存在于数据库中并且它附加到上下文中,所以我不明白为什么 EF 试图插入它。我的附加方法看起来像这样
public void Attach<T>(T entity)
where T : class, IEntity
{
EntityState state = context.Entry<T>(entity).State;
if (state == EntityState.Detached)
{
IEnumerable<T> local = (IEnumerable<T>)context.Set<T>().Local;
bool alreadyAtContext = local.Contains(entity, new EntityComparer());
if (!alreadyAtContext)
{
context.Set<T>().Attach(entity);
}
}
}
}