It is possible to create the MySecondEntity
object manually, and attach it to the context as an unchanged object.
var secondEntity = new MySecondEntity();
secondEntity.Id = id;
context.MySecondEntities.Attach(secondEntity);
entity.SecondEntity = secondEntity;
To keep it simple, I have ignored the possibility that a MySecondEntity
object with the same key already exists in the context. To make that work, you should check the local entities (for example by searching context.MySecondEntities.Local
) and re-use an entity if you find it in there.
Note: EF won't have any way of knowing that the other properties of secondEntity
, which are left at their default values, don't correspond to what's in the database. For what you're doing now, that doesn't matter, but it may matter at a later stage.