我在使用 Entity Framework 6、Code First Fluent API 时遇到了一些不符合惯例的问题。
一个典型的例子是我有一个名为软件的实体。我不希望数据库表被称为 Softwares。它应该被称为软件。但也有一些其他的偏离。
问题是,为外键创建了 2 列,而应该只创建 1 列。例如,在我的域中,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);
}
这就是创建一个软件ID列和一个软件_Idsdf 数据库中的列。
有谁知道我如何才能以这种方式背离惯例?
Cheers
双外键与表的重命名无关。
去除
modelBuilder.Entity<SoftwareFile>().HasRequired(s => s.Software).WithMany().HasForeignKey(s => s.SoftwareId);
line.
这行代码表示有一个一面之间的一对多关系Software
and SoftwareFile
应该使用SoftwareId
属性作为外键。
But you do have a SoftwareFiles
属性于Software
,这使得 EF 假设您想要定义第二个,两面性,您选择不为其提供显式外键的两个实体之间的一对多关系。
因此,EF 通过创建第二个外键属性来解决这个问题,名为Software_Id
!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)