我在使用 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列。
有谁知道我怎样才能以这种方式脱离惯例?
干杯