【问题标题】:How do I setup a foreign key relationship in codefirst without using a navigation property?如何在不使用导航属性的情况下在 codefirst 中设置外键关系?
【发布时间】:2011-10-29 14:42:52
【问题描述】:

假设您有一个带有订单状态的订单类,我想在 OrderStatus 类中声明 OrderStatusId。但是,默认情况下没有设置外键关系。如果我在列上使用 [ForeignKey] 属性,它似乎需要一个我不想要的导航属性,因为这意味着必须在我的所有查询中对导航属性执行连接以检查状态。

如何在 EF codefirst 中实现这一点?不使用导航属性将属性定义为外键。

public class Order
{
  public int OrderId;

  public int OrderStatusId;
  // properties...
}

public class OrderStatus
{
  public int OrderStatusId;
  public string Status;
}

【问题讨论】:

    标签: entity-framework ef-code-first code-first


    【解决方案1】:

    您始终需要 at least one side 上的导航属性来建立关系。如果您没有导航属性,则没有任何东西可以绑定您的外键,它将保持为公共列。

    【讨论】:

    • 附带说明,将 CODE FIRST... 与 FK 值而不是引用一起使用几乎没有意义。
    • 不确定你的意思。
    • 他的意思是你可以创建对象的集合而不必在模型中暴露外键值
    【解决方案2】:

    改为这样创建模型

    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 将使用您的导航属性自行创建外键 没有理由将它们暴露给模型,因为您可以在必要时使用导航属性访问 id

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多