EntityFramework Fluent API Foreign Key Order

How do I set the column order for foreign key properties so that all columns are generated in my user order and not alphabetically by default?

I want to use clean aproach code first without any annotation attributes, and I don't want to include columns of foreign key identifiers in my object (e.g. UserId, RoleId, etc.).

Say I have the following configuration class:

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 will generate the following table:

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

But I want:

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

UPDATE: A workaround was found using the properties of the secure foreign key:

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);
    }
}

Is there any other way to achieve the same?

+3
source share
1 answer

AFAIK, , .
? FK protected, .

-1

All Articles