如何删除Entity Framework 4.1生成的外键名称中的下划线

Aca*_*uza 7 .net entity-framework data-annotations entity-framework-4.1

我有一个使用Entity Framework 4.1的关系,我的外键是自动生成的,外键的名称有下划线:

public class Setor : Entity
{
    public long Id { get; set; }
    public string Nome { get; set; }
    public virtual Secretaria Secretaria { get; set; }
}

public class Secretaria : Entity
{
    public long Id { get; set; }
    public string Nome { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这在表Setor中生成了名为:Secretaria_Id的外键

我想删除这个下划线:SecretariaId

有没有办法做到这一点?我更喜欢使用DataAnnotations.

Sla*_*uma 9

在Fluent API中,您可以为FK列指定名称:

modelBuilder.Entity<Setor>()
    .HasOptional(s => s.Secretaria)
    .WithMany()
    .Map(a => a.MapKey("SecretariaId"));
Run Code Online (Sandbox Code Playgroud)

我认为DataAnnotations无法做到这一点.或者,您可以将外键公开到模型类中,如下所示:

public class Setor : Entity
{
    public long Id { get; set; }
    public string Nome { get; set; }
    public long? SecretariaId { get; set; }
    public virtual Secretaria Secretaria { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

约定将自动识别,因为FK和列名称将是属性的名称,即SecretariaId.

  • 如果您没有在模型中为外键使用属性,那么使用数据注释,您也可以使用[Column(“ ColumnName”)]属性使用流利的api来完成此操作,但是您可能会被困于使用fluent tho (2认同)