私はこのようなモデルを持っています:
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);
}
}
}
}