【发布时间】:2016-06-08 20:38:46
【问题描述】:
我正在尝试将 Asp.Net MVC 框架与 Microsoft 开箱即用的内置身份系统结合使用。
但是,我需要获取更多关于用户的数据。
为了最大限度地减少对身份类的更改,我需要创建一个名为“用户”的新模型,在其中放入所有自定义属性。然后我添加了一个名为“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?
-
这听起来是个好主意。当我这样做时,我会有一两个模型吗?从数据视图来看,我会有一个表而不是两个表吗?
-
应该只有一个,但我不记得我有几年没有这样做了。
标签: c# asp.net-mvc entity-framework asp.net-identity identity