Skip to content

Instantly share code, notes, and snippets.

@joe-oli
Last active January 17, 2019 12:14
Show Gist options
  • Save joe-oli/aec9fb60f863adbd9849401edece6c3d to your computer and use it in GitHub Desktop.
Save joe-oli/aec9fb60f863adbd9849401edece6c3d to your computer and use it in GitHub Desktop.
Entity Framework attached + detached entities
int pkSeqNo = 123;
//detached entity
MyChildEntity child_entity = new MyChildEntity();
MyParentEntity attachedParentEntity = dbCtx.MyParentEntity
.Where( h => h.seqNo == pkSeqNo)
.Include( h => h.MyChildEntity)
.SingleOrDefault();
//version 1: you can get a handle on the added entity...
MyChildEntity inserted = dbCtx.MyChildEntity.Add(child_entity);
//version 2: returns void, no handle to the added entity...
attachedParentEntity.MyChildEntity.Add(child_entity); //NB: the nav prop .MyChildEntity in this line is actually a collection ICollection<MyChildEntity>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment