先用代码定义外键

本文关键字:定义 代码 | 更新日期: 2023-09-27 18:15:33

我试图定义两个表与ForeignKeyAttribute之间的关系。我遇到了一些网站,描述了一种有趣的方法,用ForeignKeyAttribute来做这件事。

下面是两个代码示例:

第一个:

public class Customer
{
    public int ID { get; set; }
    public int OrderID { get; set; }
    // Some other properties
    [ForeignKey("OrderID")]
    public virtual Order Order { get; set; }
}
public class Order
{
    public int ID { get; set; }
    public int CustomerID { get; set; }
    // Some other properties
    [ForeignKey("CustomerID")]
    public virtual Customer Customer { get; set; }
}

第二个:

public class Customer
{
    public int ID { get; set; }
    [ForeignKey("Order")]
    public int OrderID { get; set; }
    // Some other properties
    public virtual Order Order { get; set; }
}
public class Order
{
    public int ID { get; set; }
    [ForeignKey("Customer")]
    public int CustomerID { get; set; }
    // Some other properties
    public virtual Customer Customer { get; set; }
}

在第一个代码示例中,ForeignKeyAttribute被放置在public virtual Customer Customer { get; set; }上。

public int CustomerID { get; set; } (Order- And CustomerID)的第二个代码示例中。

我的问题是,我如何知道在哪种情况下使用哪种方法?

我知道这也可以用Fluent API来完成,但这在这个问题上是不相关的。

先用代码定义外键

首先,只想说您不需要将ForeignKey属性放在任何属性上。只需做以下操作就足够了:

public class Customer
{
    public int ID { get; set; }
    //EF will create the relationship since the property is named class+id
    //the following is not necessary, is just good practice
    //if this is omitted EF will create a Order_Id on its own
    public int OrderID { get; set; }
    // Some other properties
    public virtual Order Order { get; set; }
}
public class Order
{    
    public int ID { get; set; }
    // no need to include the id property
    // Some other properties
    public virtual Customer Customer { get; set; }
}

话虽如此,答案是ForeignKey构造接受一个字符串形参。如果你把它放在外键属性上,它应该有导航属性的名字,如果你把它放在导航属性上,它应该有外键的名字。你把它放在哪里完全取决于你,只要你记住使用什么string值。