【发布时间】: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