What is the best way to set navigation property having only id in Entity Framework?

c#, entity-framework, entity-framework-6, navigation-properties

Solution

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.

Problem

I have the next enitities: ``` public class MyEntity { public virtual int Id { get; set; } public virtual MySecondEntity SecondEntity { get; set; } } public class MySecondEntity { public virtual int Id { get; set; } ... some properties here ... } ``` I don't want to create MySecondEntityID property in order to have clean model. I need to set myEntity.MySecondEntity by its Id, but I don't want to request MySecondEntity from DB. Is it possible to do it without creating MyEntity.MySecondEntityID property and without loading the whole MySecondEntity object or even without any db requests?

Original source

Related problems