c# - EntityFramework trying to insert unchanged attached entity -


i have model this:

public class parent {     public childa childa { get; set;}     public childb childb { get; set;} } 

in cache store collection of such objects statistics. when i'm trying save collection, error childa cannot added violation primary key 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 exists in database , attached context, don't why ef trying insert it. attach method looks this

public void attach<t>(t entity)         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);             }         }     } } 


Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -