Malcolm O'Hare
Malcolm O'Hare

Reputation: 4999

Entity Framework: Map Foreign Key without Navigation Property?

Motivation : My EF4.1 DbContext is saving Entities in the wrong order

Reason : Lack of navigation properties on my models

How I want to fix it :

I want to set up foreign key relationships in my DbContext. The catch is that my entity objects have no navigation properties (I'm using it to populate a web service and then firing DTO objects over to my application).

The classes below would be an example. In MinorClass, I want to configure my context so that it knows MajorClassID is a foreign key. The articles I've been finding on the internet on how to explicitly define Foreign Keys involve using navigational properties, which my objects dont have.

Is there a way to map this relationship?

public class MinorClass
{
    public Guid ID {get;set:}
    public Guid MajorClassID {get;set;} // foreign key
    public string Name {get;set;}
}

public class MajorClass
{
    public Guid ID {get;set;}
    public string Name {get;set;}
}

Upvotes: 3

Views: 2655

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364249

Navigation property is primary construct whereas foreign key is helper (imho wrong helper). EF recognizes ordering of DB commands by relationships which are defined by navigation properties. You cannot define relation just by foreign key. You need navigation property on at least one side of the relation.

Upvotes: 5

Related Questions