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

时间:2012-03-21 23:38:35

标签: c# entity-framework

使用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`}

其中,最后两列不存在。

4 个答案:

答案 0 :(得分:4)

您可以使用数据注释或Fluent API执行此操作

属性方式

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

流利的方式

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

响应更新

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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

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

外键关联

[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<SomeEntity>()
    .HasRequired(e => e.SomeOtherName)   // or .HasOptional(...)
    .WithMany()
    .HasForeignKey(e => e.VeryDifferentFKPropertyName);

modelBuilder.Entity<SomeEntity>()
    .Property(e => e.VeryDifferentFKPropertyName)
    .HasColumnName("JustAnotherColumnName");

独立协会

public virtual MyObject SomeOtherName { get; set; }

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

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