【发布时间】:2017-06-07 15:46:03
【问题描述】:
嘿,我像这样将 Teams 添加到了我的 ApplicationUser:
public class ApplicationUser : IdentityUser
{
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;
}
public virtual ICollection<Function> Functions { get; set; }
public virtual ICollection<Participation> Participations { get; set; }
public virtual ICollection<Team> Teams { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Mobile { get; set; }
public DateTime Birthdate { get; set; }
}
在我的控制器中,我想为用户添加一个新团队:
ApplicationUser user = UserManager.GetUserById(dto.PersonId[0]);
if (user != null)
{
if (user.Teams == null)
{
user.Teams = new List<Team>();
}
user.Teams.Add(mannschaft);
mannschaft.UsersId.Add(user?.Id);
uow.SaveChanges();
Team team = uow.RepTeam.Get(t => t.Bezeichnung == dto.Name).FirstOrDefault();
return Request.CreateResponse(HttpStatusCode.Created, team?.Id);
}
所以团队被添加到 IdentityUser 没有问题,但是当我想像这样调用不同控制器中的所有团队时:
ApplicationUser user = UserManager.GetUserById(userid);
ICollection<DtoTeam> foo = new List<DtoTeam>();
if (user != null)
{
foreach (var teams in user.Teams)
{
foo.Add(uow.RepTeam.GetByKey(teams).ToDto());
}
}
return foo;
表示用户中没有团队...
【问题讨论】:
-
您正在混合上下文。有您的身份上下文(其中包含 AspNet... 表),还有您的自定义上下文,其中应包含用户、团队、功能、参与者等表。身份是关于识别用户的。这与您的自定义上下文无关。您应该尝试区分这些问题。
-
感谢您的快速答复。我明白了,但在我的应用程序中,一个用户可以在一个团队中,所以我应该添加一个新的实体人员,我保存身份 ID 和团队等等?我已经考虑过这个解决方案,但不知道它是否好。
-
是的,使用自己的用户表设置单独的自定义模型。严格来说,身份模型只是关于身份的。您甚至可以将身份表存储在不同的数据库中,或者您可以使用外部服务登录(如 IdentityServer)。所以自定义模型实际上对身份一无所知,而身份模型对自定义模型一无所知。这意味着两者之间没有任何关系。除了您可以将登录用户链接到自定义用户之外。您可以通过添加带有用户 ID 的声明来做到这一点。
-
是的,成功了!现在将尝试将身份用户表保存在单独的数据库中。我所要做的就是更改身份用户上下文的连接字符串。对吗?
-
是的,没错。您将需要两个连接字符串,一个用于身份上下文,一个用于您的自定义上下文。不过,您不必将身份表存储在单独的数据库中。
标签: c# asp.net-web-api asp.net-identity