如何在不使用导航属性的情况下在 codefirst 中设置外键关系?
假设您有一个带有订单状态的订单类,我想在 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您始终需要 至少一侧建立关系。如果您没有导航属性,则没有任何东西可以绑定外键,它将保留为公共列。
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.
像这样创建模型,
EF 将使用您的导航属性自行创建外键
没有理由将它们暴露给模型,因为没有必要,您可以在必要时使用导航属性访问 id
Create your model like this instead
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