[英]extending PrimaryKey of IdentityUserRole in Identity 2
是否可以通過附加列擴展ApplicationUserRole的主鍵?
默認情況下,有兩列定義為主鍵: UserId
和RoleId
這是默認實現
public partial class ApplicationUserRole : IdentityUserRole<string>
{
public virtual ApplicationUser User { get; set; }
public virtual ApplicationRole Role { get; set; }
}
public class IdentityUserRole<TKey>
{
public IdentityUserRole();
// Summary:
// RoleId for the role
public virtual TKey RoleId { get; set; }
//
// Summary:
// UserId for the user that is in the role
public virtual TKey UserId { get; set; }
}
和數據庫中的表看起來像
CREATE TABLE [dbo].[AspNetUserRoles](
[UserId] [nvarchar](128) NOT NULL,
[RoleId] [nvarchar](128) NOT NULL,
CONSTRAINT [PK_dbo.AspNetUserRoles] PRIMARY KEY CLUSTERED
(
[UserId] ASC,
[RoleId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
但我還需要更多! :)我的意思是我希望我的模型看起來像
public partial class ApplicationUserRole : IdentityUserRole<string>
{
public Guid ServiceId { get; set; }
public virtual ApplicationUser User { get; set; }
public virtual ApplicationRole Role { get; set; }
public virtual Service Service { get; set; }
}
我無法理解如何正確使用數據注釋或流利的api。 我都嘗試了兩次都沒有成功。 看來遷移引擎會忽略該模型的任何主鍵更改。 至少當我添加注釋或流利的api方法時,遷移引擎會生成空的遷移腳本。
我剛剛添加了serviceId屬性,我的表現在看起來像
CREATE TABLE [dbo].[AspNetUserRoles](
[UserId] [nvarchar](128) NOT NULL,
[RoleId] [nvarchar](128) NOT NULL,
[ServiceId] [uniqueidentifier] NOT NULL,
CONSTRAINT [PK_dbo.AspNetUserRoles] PRIMARY KEY CLUSTERED
(
[UserId] ASC,
[RoleId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
當我嘗試通過注釋或流暢的api遷移腳本應用關鍵更改時,
public partial class rolesmigrate02 : DbMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
流利的api:
modelBuilder.Entity<ApplicationUserRole>().HasKey(hk => new { hk.UserId, hk.RoleId, hk.ServiceId});
注釋
public partial class ApplicationUserRole : IdentityUserRole<string>
{
[Key, Column(Order = 0)]
public override string UserId { get; set; }
[Key, Column(Order = 1)]
public override string RoleId { get; set; }
[Key, Column(Order = 2)]
public Guid ServiceId { get; set; }
public virtual ApplicationUser User { get; set; }
public virtual ApplicationRole Role { get; set; }
public virtual Service Service { get; set; }
}
我可以在數據庫中手動進行更改,但我懷疑
我的錯誤在哪里? 為什么我不能通過代碼優先遷移來擴展此模型?
花了一些時間后,我在StackOverflow上找到了有關Sam 2的帖子
關鍵是在base.OnModelCreating(modelBuilder)
如果我們要重新應用或修改預定義的身份2映射,則應在base.OnModelCreating之后進行。
所以流利的api應該看起來像
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// usualy i put this line to the end of this method but it should be before
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ApplicationUserRole>().HasKey(hk => new { hk.UserId, hk.RoleId, hk.ServiceId});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.