2013-02-17 89 views
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與任何Bicycle都沒有關聯。大部分將與多個Bicycle實體關聯。

我有以下流利的API代碼來設置FK關係:

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

這一切似乎很好地工作。但是,我真的想要從Bicycle實體中刪除BicycleManufacturerId屬性。它只是在那裏建立FK關係。如果我刪除此屬性,是否有辦法創建正確的FK關係?通過增加對對方作爲一個集合的關係

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

回答

3

您可以刪除屬性和使用映射。

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; } 
    } 
0

您也可以按照慣例做到這一點:

相關問題