我正尝试使用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