1

我有以下课程:

   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与 any 无关Bicycle。大多数将与多个Bicycle实体相关联。

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

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

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

4

2 回答 2

3

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

modelBuilder.Entity<Bicycle>()
    .HasRequired(a => a.BicycleManufacturer)
    .WithMany()
    .Map(m => m.MapKey("BicycleManufactuerId"));
于 2013-02-17T16:42:49.890 回答
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; }
    }
于 2013-02-17T18:09:37.503 回答