如何在不使用导航属性的情况下在codefirst中设置外键关系? [英] How do I setup a foreign key relationship in codefirst without using a navigation property?

查看:705
本文介绍了如何在不使用导航属性的情况下在codefirst中设置外键关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



如何在EF codefirst中完成这个?在不使用导航属性的情况下将属性定义为外键。

  public class Order 
{
public int OrderId;

public int OrderStatusId;
//属性...
}

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

解决方案

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.

这篇关于如何在不使用导航属性的情况下在codefirst中设置外键关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆