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

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

Question

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?

1
8
2/6/2014 8:42:12 AM

Accepted Answer

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.

8
2/6/2014 8:50:55 AM

Popular Answer

Use a mutator method to modify a protected property for the ID:

public class MyEntity
{
    public virtual int Id { get; set; }
    public virtual MySecondEntity SecondEntity { get; set; }

    [ForeignKey( "SecondEntity" )]
    protected virtual int? MySecondEntityId { get; set; }

    public void SetSecondEntityId( int? id )
    {
        MySecondEntityId = id;
    }
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow