外键导航属性命名约定替代方案

使用Entity Framework 4.1时,是否有导航属性命名约定的替代方法?

例如,而不是这样做:

public virtual MyObject MyObject { get; set; } 

成为

 public virtual MyObject SomeOtherName { get; set; } 

更新:

当添加[ForeignKey("OldStepId")][ForeignKey("NewStepId")]属性时,生成的SQL将变为:

 {SELECT `Extent1`.`CompletedId`, `Extent1`.`OldStepId`, `Extent1`.`NewStepId`, `Extent1`.`Name`, `Extent1`.`Step_StepId`, `Extent1`.`Step_StepId1` FROM `Completed` AS `Extent1`} 

其中,最后两列不存在。

您可以使用Data Annotations或Fluent API执行此操作

属性方式

 public virtual Int32 MyObjectId{get;set;} [ForeignKey("MyObjectId")] public virtual MyObject SomeOtherName { get; set; } 

流利的方式

 modelBuilder.Entity() .HasRequired(p => p.SomeOtherName) .WithMany(d => d.Type) .HasForeignKey(p => p.MyObjectId) 

对更新的回应

如果MyOjbect类中有List,则需要将该List标记为[InverseProperty("SomeOtherName")] 。 这可能是您在SQL中获得额外列的原因。 通过告诉生成器主列确实在哪里,这可以防止双向关系加倍。

我通常称它们与Nav Props的外键相同。

如果您添加T4模板来生成内容,您几乎可以根据需要调整命名方案…

你可以随意命名。 您必须区分具有在类中公开的(标量)外键属性的导航属性(“外键关联”)和没有(“独立关联”)的导航属性:

外国关键协会

 [ForeignKey("VeryDifferentFKPropertyName")] // refers to property, NOT column public virtual MyObject SomeOtherName { get; set; } [Column("JustAnotherColumnName")] // map property to column name public int VeryDifferentFKPropertyName { get; set; } 

使用Fluent API:

 modelBuilder.Entity() .HasRequired(e => e.SomeOtherName) // or .HasOptional(...) .WithMany() .HasForeignKey(e => e.VeryDifferentFKPropertyName); modelBuilder.Entity() .Property(e => e.VeryDifferentFKPropertyName) .HasColumnName("JustAnotherColumnName"); 

独立协会

 public virtual MyObject SomeOtherName { get; set; } 

您只能使用Fluent API映射外键列名:

 modelBuilder.Entity() .HasRequired(e => e.SomeOtherName) // or .HasOptional(...) .WithMany() .Map(a => a.MapKey("JustAnotherColumnName"));