c# - Entity Framework blowing up when attaching collection of new entities with same (empty) ID -
i trying save entities entity framework one-to-many relationship. person, , personphone, person has 0 or more personphone. working on detached entities , trying attach them context. have existing (already in database) person , trying add 2 new personphone it:
existingperson.personphones = new list<personphone>(); existingperson.personphones.add(new personphone(){ fk_personid = existingperson.id }; existingperson.personphones.add(new personphone(){ fk_personid = existingperson.id }; the 2 new personphone have guid primary key equal guid.empty.
so pass existingperson , existingperson.personphones collection save method in business logic because want validate each object before attaching dbcontext. has code validate given person, attach dbcontext, each personphone validate , attach dbcontext. problem i'm having when try attach person following code, following error:
if (entity.id == guid.empty) dbcontext.entry(entity).state = entitystate.added; else dbcontext.entry(entity).state = entitystate.modified; attaching entity of type 'datamodels.personphone' failed because entity of same type has same primary key value. can happen when using 'attach' method or setting state of entity 'unchanged' or 'modified' if entities in graph have conflicting key values. may because entities new , have not yet received database-generated key values. in case use 'add' method or 'added' entity state track graph , set state of non-new entities 'unchanged' or 'modified' appropriate.
so starters, guess shouldn't have existingperson reference personphone list if want attach them separately because seems smart enough attach them both in single call. why isn't smart enough know empty ids indicate added. personphone.id property has storegeneratedpattern = identity in edmx feel if it's going try automatically attach it, should know use entitystate.added if pk guid.empty. otherwise supposed do? says the 'added' entity state track graph it's 1 attaching entity, don't have chance that.
Comments
Post a Comment