How do I setup a foreign key relationship in codefirst without using a navigation property?

梦想与她 提交于 2019-12-24 00:48:39

问题


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

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/7104895/how-do-i-setup-a-foreign-key-relationship-in-codefirst-without-using-a-navigatio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!