【问题标题】:Defining ForeignKeys with Code First使用代码优先定义外键
【发布时间】:2013-05-25 11:33:07
【问题描述】:

我正在尝试使用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 来完成,但目前与这个问题无关。

【问题讨论】:

    标签: c# ef-code-first foreign-key-relationship


    【解决方案1】:

    首先,只想说您不需要将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 值。

    【讨论】:

    • 你好,关于你的最后一行,除此之外,使用哪种方法没有区别?
    • 是的,ForeignKey 的放置位置没有区别
    猜你喜欢
    • 1970-01-01
    • 2013-07-29
    • 2011-05-15
    • 2018-02-13
    • 2013-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多