3

Say you have an order class with an order status, I want to declare the OrderStatusId inside the OrderStatus class. However, no foreign key relationship is set-up by default. If I use [ForeignKey] attribute on the column it seems to demand a navigation property which I don't want as this would mean having to carry out joins on the navigation property in all of my queries just to check the status.

How do I accomplish this in EF codefirst? Define a property as a foreign key without using a navigation property.

public class Order
{
  public int OrderId;

  public int OrderStatusId;
  // properties...
}

public class OrderStatus
{
  public int OrderStatusId;
  public string Status;
}
jaffa
  • 26,770
  • 50
  • 178
  • 289

2 Answers2

4

You always need navigation property on at least one side to build a relation. If you don't have navigation properties you have nothing to bind your your foreign key with and it will remain as common column.

Community
  • 1
  • 1
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
0

Create your model like this instead

public class Customer 
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string StreetAddress { get; set; }
    //etc...

    //navigation properties 
    public virtual List<Order> Orders { get; set; }

}

public class Order 
{

    public int Id { get; set; }
    public string OrderStatus { get; set; }

    //navigation properties 
    public virtual Customer OrderedBy { get; set; }

    //etc..


}

EF will create your foreign keys on its own using you navigation properties no reason to expose them to the model as it is unnecessary you can access the id if necessary using the navigation properties

Chris McGrath
  • 1,727
  • 3
  • 19
  • 45