3

我在使用 Entity Framework 6,Code First Fluent API 时遇到了一些偏离约定的问题。

一个典型的例子是我有一个名为 Software 的实体。我不希望将 db 表称为 Softwares。它应该被称为软件。但也有一些其他的出发点。

问题是,为外键创建了 2 列,而外键应该只有 1 列。例如,在我的域中,SoftwareFiles 和 Software 之间是 1:m 的关系。(逻辑是可能有多个文件与一个软件相关,例如,由于服务包,Windows XP 将有多个与之关联的 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);
    }

那就是在 sdf 数据库中同时创建一个SoftwareId列和一个Software_Id列。

有谁知道我怎样才能以这种方式脱离惯例?

干杯

4

1 回答 1

1

双外键与表的重命名无关。

去除那个

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

线。

这行代码表示两者之间存在单向的一对多关系,Software并且SoftwareFile应该使用该SoftwareId属性作为外键。

但是您确实有一个SoftwareFiles属性 on Software,这使 EF 假定您要在您选择不为其提供显式外键的两个实体之间定义第二个、双面的、一对多的关系。

因此,EF 通过创建名为Software_Id!的第二个外键属性来进行救援。

于 2013-11-10T08:55:21.580 回答