0

我正在尝试使用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- 和 CustomerID)上的第二个代码示例中。

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

我知道这也可以使用 来完成Fluent API,但目前与这个问题无关。

4

1 回答 1

0

首先,只想说您不需要将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要使用的价值,您将其放置在哪里完全取决于您。

于 2013-05-25T12:51:52.927 回答