我可以避免实体中的外键属性吗?

时间:2013-02-17 16:38:03

标签: entity-framework ef-code-first

我有以下课程:

   public class Bicycle
    {
        public int BicycleId { get; set; }
        public DateTime YearOfManufacture { get; set; }
        public int BicycleManufactuerId { get; set; }
        public BicycleManufacturer BicycleManufacturer { get; set; }
    }

    public class BicycleManufacturer
    {
        public int BicycleManufacturerId { get; set; }
        public string Description { get; set; }
    }

每个Bicycle必须有BicycleManufacturer(1:1)。某些BicycleManufacturer可能与任何Bicycle无关。大多数将与多个Bicycle实体相关联。

我有以下流畅的API代码来设置FK关系:

    modelBuilder.Entity<Bicycle>()
        .HasRequired(a => a.BicycleManufacturer)
        .WithMany()
        .HasForeignKey(u => u.BicycleManufactuerId);

这一切似乎都很好。但是,我真的想从BicycleManufacturerId实体中删除Bicycle属性。它只是建立FK关系。如果我删除这个属性,有没有办法可以创建正确的FK关系?

2 个答案:

答案 0 :(得分:3)

您可以删除该属性并使用映射:

modelBuilder.Entity<Bicycle>()
    .HasRequired(a => a.BicycleManufacturer)
    .WithMany()
    .Map(m => m.MapKey("BicycleManufactuerId"));

答案 1 :(得分:0)

您也可以按惯例通过将另一方的关系添加为集合来实现。

public class Bicycle
    {
        public int BicycleId { get; set; }
        public DateTime YearOfManufacture { get; set; }
        public int BicycleManufactuerId { get; set; }
        public BicycleManufacturer BicycleManufacturer { get; set; }
    }

    public class BicycleManufacturer
    {
        public int BicycleManufacturerId { get; set; }

        public ICollection<Bicycle> Bicycles { get; set; }

        public string Description { get; set; }
    }