How do I setup a foreign key relationship in codef

2019-07-17 11:47发布

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

2条回答
一纸荒年 Trace。
2楼-- · 2019-07-17 12:17

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.

查看更多
聊天终结者
3楼-- · 2019-07-17 12:23

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

查看更多
登录 后发表回答