【问题标题】:Extend IdentityUser, foreign key constraint conflict扩展IdentityUser,外键约束冲突
【发布时间】:2019-10-08 23:29:10
【问题描述】:

我想使用 ASP.Net-Identity 进行用户管理。为此,我想用一些属性扩展IdentityUser 类。

public class AppUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<AppUser> manager)
    {
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        return userIdentity;
    } 

    public int Settings_ID { get; set; }
    public string Position { get; set; }
    public string CompanyName { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }
[...]

现在,在我的data context 中,我只想为这个用户模型创建一个表:

 public class AntContext : IdentityDbContext<AppUser>
{

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Database.SetInitializer<AntContext>(null);
        modelBuilder.Entity<AppUser>().ToTable("AppUsers");
        base.OnModelCreating(modelBuilder);
    }
        public override IDbSet<AppUser> Users { get; set; }
[...]

但是,当我尝试update-database 时,我收到错误:

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.AppUsers_dbo.AspNetUsers_Id". The conflict occurred in database "C:\USERS\NEUMA\SOURCE\REPOS\MYANTON\MYANTON\APP_DATA\ASPNETDB.MDF", table "dbo.AspNetUsers", column 'Id'.

我知道AspNetUsers 是来自IdentityUser 的一个表,但是如何只创建一个表才能不发生冲突?

如何正确扩展 IdentityUserclass 并在我的数据上下文中使用它?

【问题讨论】:

    标签: c# asp.net-mvc asp.net-identity


    【解决方案1】:

    解决方案是不要混合上下文。保持关注点分开。使用身份迁移脚本并为业务上下文(您的数据上下文)创建一个新脚本。

    将用户表添加到引用来自 IdentityContext 的名称或子的业务上下文。请阅读我的回答 here 以了解非常相似的问题。

    此外,无需扩展 ApplicationUser 表。您可以使用 AspNetUserClaims 添加此类信息。使用自定义类型:

    new Claim("http://www.myapp.com/Firstname", "Firstname");
    

    或现有的WIF ClaimType

    new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname", "Lastname");
    

    对于 CompanyName,这实际上可能是业务上下文的一部分。

    【讨论】:

    • 我接受了你的回答,因为这对我来说似乎是合乎逻辑的。如果我理解正确,我会使用我的业务逻辑创建一个Users 表,并保留IdentityUser 原样。我的User 将如何被引用到他们各自的Identity - 只需引用Id
    • 是的,AspNetUsers.Id 的值应该在声明(sub,userid)中可用。您可以使用它来引用用户。通过这种方式,您可以将当前用户链接到 DataContext.User(作为外键),其中 DataContext.User.Id 可以是自动编号并用于与用户的 DataContext 关系。
    猜你喜欢
    • 2017-12-31
    • 1970-01-01
    • 1970-01-01
    • 2018-07-26
    • 1970-01-01
    • 2018-04-25
    • 1970-01-01
    • 2021-04-29
    • 1970-01-01
    相关资源
    最近更新 更多