2013-11-10 41 views
3

我遇到了一些使用實體框架6 Code First Fluent API偏離慣例的問題。代碼首先多個外鍵的一對多關係

一個典型的例子是我有一個名爲Software的實體。我不希望數據庫表被稱爲軟件。它應該被稱爲軟件。但還有一些其他的偏離。

問題是,只有1個應該是外鍵創建2列。例如,在我的域中,SoftwareFiles和Software之間是1:m的關係。 (由於服務包的原因,可能有超過1個文件與一個軟件相關,例如Windows XP將有超過1個ISO相關聯)。

的文件:

public class Software 
{ 
    public string Description { get; set; } 
    public int Id { get; set; } 
    public SoftwareType Type { get; set; } 
    public int TypeId { get; set; } 

    public virtual ICollection<SoftwareFile> SoftwareFiles { get; set; } 
} 

public class SoftwareFile 
{ 
    public int Id { get; set; } 
    public string FileName { get; set; } 
    public FileTypes FileType { get; set; } 
    public string Name { get; set; } 
    public Software Software { get; set; } 
    public int SoftwareId { get; set; } 
} 

    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     // Set up the SoftwareFile table 
     modelBuilder.Entity<SoftwareFile>().Property(s => s.FileName).HasMaxLength(250).IsRequired().IsVariableLength(); 
     modelBuilder.Entity<SoftwareFile>().Property(s => s.FileType).IsRequired(); 
     modelBuilder.Entity<SoftwareFile>().HasRequired(s => s.Software).WithMany().HasForeignKey(s => s.SoftwareId); 

     modelBuilder.Entity<Software>().ToTable("Software"); 
     modelBuilder.Entity<Software>().Property(s => s.Description).HasMaxLength(250).IsOptional().IsVariableLength(); 
     modelBuilder.Entity<Software>().HasRequired(s => s.Type).WithMany().HasForeignKey(t => t.TypeId); 


     base.OnModelCreating(modelBuilder); 
    } 

即創建既是SoftwareId列和自衛隊數據庫Software_Id列。

有沒有人知道我如何能以這種方式離開公約?

Cheers

回答

1

雙重外鍵與表的重命名沒有關係。

取出

modelBuilder.Entity<SoftwareFile>().HasRequired(s => s.Software).WithMany().HasForeignKey(s => s.SoftwareId); 

線。

這行代碼說有一個片面一個SoftwareSoftwareFile之間有很多關係,即應使用SoftwareId屬性爲外鍵。

但你SoftwareFiles財產上Software,這使得EF假設你要定義一個第二,雙面,一個爲你選擇不提供明確的兩個實體之間的多對多關係外鍵。

因此EF通過創建第二個外鍵屬性Software_Id來解救!

+0

是的,那工作。它也清除了我在問題中沒有包括的另一種關係。感謝您的協助! – onefootswill

相關問題