【问题标题】:EntityFramework Fluent API Foreign Key orderingEntityFramework Fluent API 外键排序
【发布时间】:2014-03-25 14:27:24
【问题描述】:

如何设置外键属性的列顺序,以便所有列都按照我的自定义顺序而不是默认的字母顺序生成?

我想使用不带任何注释属性的纯代码优先方法,并且我不想在我的实体中包含外键 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);
    }
}

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 感谢您的评论。我想省略它们以获得清晰的对象模型界面。将导航属性和外键属性放在同一个类中会形成一个科学怪人实体:) 您将它们隐藏在protected 下的想法实际上很好。我会将此解决方法添加到问题中。
    • 很简单,有些人认为根本不应该公开数据库密钥。这样,如果数据库结构发生变化,您就不需要修复它。 Db Keys 更改的频率超出了我的预期……根据我的经验。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-31
    • 1970-01-01
    相关资源
    最近更新 更多