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 am capable of the following:

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

For a clean model, I don't want to establish the MySecondEntityID property.

MyEntity must be set. I can find MySecondEntity by its Id, but I don't want to ask the database for it.

Can I accomplish this without creating a MyEntity? Without loading the entire MySecondEntity object or even without making any DB requests, how can I access the MySecondEntityID property?

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

Accepted Answer

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

Popular Answer

Modify a protected property for the ID using a mutator method:

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