映射实体中具有外键的EF Code First Entity Mapping

时间:2015-02-16 13:34:12

标签: entity-framework ef-code-first data-annotations

Demo Model http://mcainsh.info/soimages/efkeyissue2.jpg

这些表仅用于示例,我要做的是在Book实体中映射虚拟制造商。我尝试过使用类似于下面的数据注释:

[ForeignKey("PublisherId")]
public virtual Publisher { get; set; }

[ForeignKey("Publisher.ManufacturerCompanyId")]
[InverseProperty("ManufacturerId")]
public virtual Manufacturer { get; set; }

这是可以做到的吗?

1 个答案:

答案 0 :(得分:0)

您正确配置了外键。要做你想做的事,你的模型应该是这样的:

public class Book
{
    public int Id { get; set; }
    public string Title{ get; set; }
    public int PublisherId { get; set; }
    [ForeignKey("PublisherId")]
    public virtual Publisher Publisher{ get; set; }

    public int ManufacturerId { get; set; }
    [ForeignKey("ManufacturerId")]
    public virtual Manufacturer Manufacturer { get; set; }
}

public class Manufacturer
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Publisher
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Book> Books  { get; set; }
}

在此模型中,您有两个一对多关系,第一个在BookPublisher之间,第二个在BookManufacturer之间。正如您在Book类中看到的,如果要使用FK属性,则必须声明与相关实体的PK类型相同的属性(请参阅PublisherIdManufacturerId )。现在,您可以将ForeignKey注释应用于导航属性,并告诉它哪个属性是关系的外键,如上所示。或者,您可以向ForeignKey添加ManufacturerId属性,以及告诉它哪个导航属性表示它是外键的关系的信息:

  [ForeignKey("Manufacturer")]
  public int ManufacturerId { get; set; }
  public virtual Manufacturer Manufacturer { get; set; }

如果您愿意,您不需要创建FKs属性,EF将为您开始工作。它将在Books表中为每个关系创建一个FK行(在执行代码后检查数据库):

public class Book
{
    public int Id { get; set; }
    public string Title{ get; set; }
    //public int PublisherId { get; set; }
    //[ForeignKey("PublisherId")]
    public virtual Publisher Publisher{ get; set; }

    //public int ManufacturerId { get; set; }
    //[ForeignKey("ManufacturerId")]
    public virtual Manufacturer Manufacturer { get; set; }
}