EntityFramework Fluent API外键排序

时间:2014-02-24 04:46:18

标签: c# entity-framework ef-code-first

如何设置外键属性的列顺序,因此所有列都将以自定义顺序生成,而不是按字母顺序生成?

我想在没有任何注释属性的情况下使用纯代码第一个aproach,我不想在我的实体中包含外键id列(如UserId,RoleId等)。

假设我有以下配置类:

public class UserRoleEntityConfiguration: EntityTypeConfiguration<UserRole>
{
    public UserRoleEntityConfiguration()
    {
        HasRequired(p => p.User).WithMany(p => p.Roles);
        HasOptional(p => p.Company).WithMany(p => p.Users);
        HasRequired(p => p.Role).WithMany(p => p.Users);
    }
}

EF将生成以下表格:

create table [dbo].[UserRoles] (
[Id] [int] not null identity,
...
[CompanyId] [int] null,
[RoleId] [int] not null,
[UserId] [int] not null,
primary key ([Id]));

但我想:

create table [dbo].[UserRoles] (
[Id] [int] not null identity,
...
[UserId] [int] not null,    
[CompanyId] [int] null,
[RoleId] [int] not null,
primary key ([Id]));

更新 找到使用受保护的外键属性的变通方法:

public class UserRole : AuditableEntity<int>
{
    protected int? CompanyId { get; set; }

    protected int RoleId { get; set; }

    protected int UserId { get; set; }

    public virtual Company Company { get; set; }

    public virtual Role Role { get; set; }

    public virtual User User { get; set; }

    public class AccessExpressions
    {
        public static readonly Expression<Func<UserRole, int?>> CompanyId = x => x.CompanyId;
        public static readonly Expression<Func<UserRole, int>> RoleId = x => x.RoleId;
        public static readonly Expression<Func<UserRole, int>> UserId = x => x.UserId;
    }
}

public class UserRoleEntityConfiguration: EntityTypeConfiguration<UserRole>
{
    public UserRoleEntityConfiguration()
    {
        Property(UserRole.AccessExpressions.UserId).HasColumnOrder(8);
        HasRequired(p => p.User).WithMany(p => p.Roles).HasForeignKey(UserRole.AccessExpressions.UserId);

        Property(UserRole.AccessExpressions.CompanyId).HasColumnOrder(9);
        HasOptional(p => p.Company).WithMany(p => p.Users).HasForeignKey(UserRole.AccessExpressions.CompanyId);

        Property(UserRole.AccessExpressions.RoleId).HasColumnOrder(10);
        HasRequired(p => p.Role).WithMany(p => p.Users).HasForeignKey(UserRole.AccessExpressions.RoleId);
    }
}

还有其他方法可以达到同样的目的吗?

1 个答案:

答案 0 :(得分:-1)

AFAIK,没有外键属性,你不能这样做。
你为什么要省略它们?如果您不想从模型外部设置它们,可以执行FK属性protected