我正嘗試使用Asp.Net MVC框架與Microsoft提供的開箱即用身份系統。如何在.Net Identity ApplicationUser模型中添加一列以指向外國模型?
但是,我需要捕獲更多關於用戶的數據。
爲了最大限度地減少對Identity類的更改,我需要創建一個名爲「User」的新模型,並在其中放入所有自定義屬性。然後我添加了一個名爲「SystemId」的屬性,它是ApplicationUser
模型的外鍵。
這裏是我做了什麼
這裏是我的自定義User
模型
[Required]
[MaxLength(128)]
[ForeignKey("Id")]
public string SystemId { get; set; }
[MaxLength(50)]
public string FirstName { get; set; }
[MaxLength(50)]
public string MiddleName { get; set; }
[MaxLength(50)]
public string LastName { get; set; }
[MaxLength(250)]
public string Email { get; set; }
[MaxLength(50)]
[Index("IX_Username", 1, IsUnique = true)]
public string Username { get; set; }
[ForeignKey("Role")]
public int RoleId { get; set; }
[ForeignKey("Client")]
public int CurrentClientId { get; set; }
[ForeignKey("Campaign")]
public int? CurrentCampaignId { get; set; }
public string Status { get; set; }
public virtual Role Role { get; set; }
public virtual Client Client { get; set; }
public virtual Campaign Campaign { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
public virtual List<UserToPrivilege> UserToPrivileges { get; set; }
public User()
{
DateTime UtcNow = DateTime.UtcNow;
Status = "active";
MiddleName = null;
UserToPrivileges = new List<UserToPrivilege>();
CreatedAt = UtcNow;
LastUpdatedAt = UtcNow;
}
}
然後在IdentityModel
類我改變了我的ApplicationUser
級以下
public class ApplicationUser : IdentityUser
{
[ForeignKey("User")]
public int UserId { get; set; }
public virtual User User { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
但是當我嘗試創建像我這樣的遷移
Add-Migration InitialCreate -Force
我收到以下錯誤
屬性「ID」不能被配置爲導航屬性。 屬性必須是有效的實體類型,並且該屬性應具有非抽象的getter和setter 。對於集合屬性,類型 必須實現ICollection,其中T是有效的實體類型。
我在做什麼錯?如何將自定義User
模型鏈接到屬於關係的ApplicationUser
模型?
你爲什麼不在User類中繼承ApplicationUser? – prospector
這聽起來像個好主意。當我這樣做,那麼我會有一個或兩個模型?從數據視圖中,我將有一個表而不是兩個? –
應該只有一個,但我不記得我在幾年內沒有這樣做。 – prospector