2013-11-10 144 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

相关问题