如何在不使用导航属性的情况下在 codefirst 中设置外键关系?

发布于 2024-11-30 16:53:52 字数 398 浏览 5 评论 0原文

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

如何在 EF codefirst 中实现此目的?将属性定义为外键,而不使用导航属性。

public class Order
{
  public int OrderId;

  public int OrderStatusId;
  // properties...
}

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

落花浅忆 2024-12-07 16:53:52

您始终需要 至少一侧建立关系。如果您没有导航属性,则没有任何东西可以绑定外键,它将保留为公共列。

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.

一抹苦笑 2024-12-07 16:53:52

像这样创建模型,

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文