3
如何設置外鍵屬性的列順序,所以所有的列將以我的自定義順序生成而不是默認的按字母順序生成?EntityFramework流利的API外鍵排序
我想使用純代碼第一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]));
UPDATE: 找到一個使用受保護的解決方法外鍵屬性:
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);
}
}
有沒有其他辦法可以達到同樣的效果?
感謝您的評論。我想省略他們有一個清晰的對象模型接口。在同一個類中擁有導航屬性和外鍵屬性使Frankenstein實體成爲可能:)您的想法隱藏在'protected'下面實際上是很好的。我會將此解決方法添加到問題中。 – Raven
很簡單,有些人認爲數據庫密鑰根本不應該暴露。這樣,如果數據庫結構發生變化,則不需要修復該問題。根據我的經驗,Db Keys的變化比我所希望的更頻繁。 – Aron
Downvoter,有什麼解釋? – Dennis