我有这样的模特:
public class Parent
{
public ChildA ChildA { get; set;}
public ChildB ChildB { get; set;}
}
在我的缓存中,我存储了这些对象的集合以进行统计。当我试图保存此集合时,我收到错误,即ChildA无法添加,因为它是违反主键constaint。
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);
}
}
}
}