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?

Was it helpful?

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.

OTHER TIPS

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;
    }
}

For entity Framework 5 or later you can add an Id next to a navigational property, which will be auto-populated when the entity is loaded from the db.

public class MyEntity 
{
    public int Id { get; set;} 

    public int MySecondEntityId { get; set;} 
    public virtual MySecondEntity MySecondEntity { get; set;} 
} 

Setting MySecondEntityId is enough to create the relationship (after saving). This way you don't have to load the actual entity from db.

If you have a nullable foreign key, the making the navigational Id nullable is enough.

public int? MySecondEntityId { get; set;} 

If you want to get the MyEntity object from your database without initializing the MySecondEntity object, you can turn off lazy loading.

Method one

Turn of lazy loading on your context.

Method two

Remove the virtual keyword from your entity:

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

This will disable lazy loading for SecondEntity. More info.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top