abp icon indicating copy to clipboard operation
abp copied to clipboard

How to link AppUser to my DomainUser

Open samquest opened this issue 6 years ago • 15 comments

According to this https://github.com/abpframework/abp/issues/773#issuecomment-477313855 what i am doing should be possible. Had issues and followed this solutions https://github.com/abpframework/abp/issues/1414#issuecomment-508818941 . I did find one similar issue here https://github.com/abpframework/abp/issues/1517

but this one is different i guess

here is the synopsis

this whole code is in a module project similar to bookstore_module example

migration runs successfully database is also created, but fails while running the service

public class AppUser : FullAuditedAggregateRoot<Guid>, IUser {
    ...
    public virtual DateTime? DateOfBirth { get; set; }
    public virtual Gender Gender { get; set; }
}
public static void ConfigureCustomUserProperties<TUser>(this EntityTypeBuilder<TUser> b)
        where TUser : class, IUser
    {
        b.Property<DateTime?>(nameof(AppUser.DateOfBirth))
            .HasColumnType("date");
        b.Property<Gender>(nameof(AppUser.Gender));
    }

public class DomainUser : FullAuditedAggregateRoot<Guid>, IMultiTenant {
    public UserType UserType { get; set; }

    public virtual Guid? TenantId { get; protected set; }
    public Guid AppUserId { get; protected set; }
    public AppUser AppUser { get; protected set; }
}


builder.Entity<AppUser>(b => {
    b.ToTable("AbpUsers");
    b.ConfigureFullAuditedAggregateRoot();
    b.ConfigureAbpUser();
    b.ConfigureCustomUserProperties();
    b.HasOne<IdentityUser>().WithOne().HasForeignKey<AppUser>(e => e.Id);
});

builder.Entity<DomainUser>(b => {
    b.ToTable(options.TablePrefix + TABLE, options.Schema);
    b.ConfigureByConvention(); //auto configure for the base class props
    b.HasOne(su => su.AppUser)
            .WithMany()
            .HasForeignKey(su => su.AppUserId);
});

and i get this error

The property 'IdentityUser.ExtraProperties' could not be mapped, because it is of type 'Dictionary<string, object>' which is not a supported primitive type or a valid entity type. Either explicitly map this property, or ignore it using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'. System.InvalidOperationException: The property 'IdentityUser.ExtraProperties' could not be mapped, because it is of type 'Dictionary<string, object>' which is not a supported primitive type or a valid entity type. Either explicitly map this property, or ignore it using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

and adding this solves the above issue builder.Entity<IdentityUser>().Ignore(x => x.ExtraProperties);

but fails with this error

The entity type 'IdentityUserLogin' requires a primary key to be defined. If you intended to use a keyless entity type call 'HasNoKey()'. System.InvalidOperationException: The entity type 'IdentityUserLogin' requires a primary key to be defined. If you intended to use a keyless entity type call 'HasNoKey()'.

samquest avatar Jan 22 '20 09:01 samquest

adding these finally made it work.

        builder.Entity<IdentityUser>().Ignore(x => x.ExtraProperties);
        builder.Entity<IdentityUserLogin>().HasKey(x => new { x.UserId, x.LoginProvider });
        builder.Entity<IdentityUserRole>().HasKey(x => new { x.UserId, x.RoleId });
        builder.Entity<IdentityUserToken>().HasKey(x => new { x.UserId, x.LoginProvider });

is this ok.

samquest avatar Jan 22 '20 14:01 samquest

  1. Which version of ABP Framework are you on?
  2. Does your module depend on AbpIdentityEntityFrameworkCoreModule?
  3. Do you call base.OnModelCreating(builder); before configuring AppUser and DomainUser?

acjh avatar Jan 22 '20 14:01 acjh

I may be experiencing the same issue while trying to load Creator user (fk CreatorId). public IdentityUser Creator { get; set; }

I've verified module and configurations as @acjh mentioned above and seems ok

[ERR] The entity type 'IdentityUserLogin' requires a primary key to be defined. If you intended to use a keyless entity type call 'HasNoKey()'. System.InvalidOperationException: The entity type 'IdentityUserLogin' requires a primary key to be defined. If you intended to use a keyless entity type call 'HasNoKey()'. at Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.ValidateNonNullPrimaryKeys(IModel model, IDiagnosticsLogger1 logger) at Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.Validate(IModel model, IDiagnosticsLogger1 logger) at Microsoft.EntityFrameworkCore.Infrastructure.RelationalModelValidator.Validate(IModel model, IDiagnosticsLogger1 logger) at Npgsql.EntityFrameworkCore.PostgreSQL.Infrastructure.NpgsqlModelValidator.Validate(IModel model, IDiagnosticsLogger1 logger)

thiag0coelho avatar Jan 22 '20 23:01 thiag0coelho

Which version of ABP Framework are you on?

acjh avatar Jan 22 '20 23:01 acjh

Tried with 1.1.2 and 2.0.0 Now I noticed I already had "AppUser" and will try to use that entity instead of IdentityUser.

Edit: I did clean + build solution, recreated database. For my entity, referenced IdentityUser for Creator property, created migration and applied, now the services I already had are working fine again. Updated to 2.0.0 and services are still working. I couldn't figure out where the error really was...

thiag0coelho avatar Jan 22 '20 23:01 thiag0coelho

Try to ignore IdentityUser:

builder.Ignore<IdentityUser>();

acjh avatar Jan 23 '20 00:01 acjh

1. Which version of ABP Framework are you on?

2.0.0, Used the CLI to spit out the MainApp(Web + API) and the CoreModule(+UnifiedWeb)

Trying to replicate BookStore-Modular and hoping to have an architecture

MyProject.WebApp (updgrade to SPI later?)
MyProject.WebAPI
MyProject.CoreModule (DomainUser is here)
MyProject.Feature1Module
MyProject.Feature2Module
...
MyProject.Feature#Module

am i doing this right? still to figure out how to share the DomainUser to Feature#Modules

2. Does your module depend on `AbpIdentityEntityFrameworkCoreModule`?

MyProject.CoreModule.EntityFrameworkCore has reference to Volo.Abp.EntityFrameworkCore (2.0.0) Volo.Abp.IdentityEntityFrameworkCore (2.0.0)

3. Do you call `base.OnModelCreating(builder);` before configuring `AppUser` and `DomainUser`?

this is the CoreModule DbContext

public class CoreDbContext : AbpDbContext<CoreDbContext>, ICoreDbContext {
    public DbSet<AppUser> Users { get; set; }
    public DbSet<DomainUser> DomainUsers { get; set; }

    public CoreDbContext(DbContextOptions<CoreDbContext> options) : base(options) { }
    protected override void OnModelCreating(ModelBuilder builder) {
        base.OnModelCreating(builder);
        builder.ConfigureCore(false);
    }
}

CoreModule DbContext configurations

public static void ConfigureCore(
    this ModelBuilder builder
    Action<CoreModelBuilderConfigurationOptions> optionsAction = null)
    {
        Check.NotNull(builder, nameof(builder));

        var options = new CoreModelBuilderConfigurationOptions(
            CoreDbProperties.DbTablePrefix,
            CoreDbProperties.DbSchema
        );


        builder.Entity<AppUser>(b =>
        {
            b.ToTable("AbpUsers");
            b.ConfigureFullAuditedAggregateRoot();
            b.ConfigureAbpUser();
            b.ConfigureCustomUserProperties();
            b.HasOne<IdentityUser>().WithOne().HasForeignKey<AppUser>(e => e.Id);              
        });


        builder.Entity<IdentityUser>().Ignore(x => x.ExtraProperties);
        builder.Entity<IdentityUserLogin>().HasKey(x => new { x.UserId, x.LoginProvider });
        builder.Entity<IdentityUserRole>().HasKey(x => new { x.UserId, x.RoleId });
        builder.Entity<IdentityUserToken>().HasKey(x => new { x.UserId, x.LoginProvider });

        optionsAction?.Invoke(options);

        builder.Entity<DomainUser>(b =>
        {
            b.ToTable(options.TablePrefix + TABLE, options.Schema);
            b.ConfigureByConvention(); //auto configure for the base class props
        });
    }

    public static void ConfigureCustomUserProperties<TUser>(this EntityTypeBuilder<TUser> b)
        where TUser : class, IUser
    {
        b.Property<DateTime?>(nameof(AppUser.DateOfBirth))
            .HasColumnType("date");
        b.Property<Gender>(nameof(AppUser.Gender));
    }

and this is my migration DbContext

public class UnifiedDbContext : AbpDbContext<UnifiedDbContext>
{
    public UnifiedDbContext(DbContextOptions<UnifiedDbContext> options)
        : base(options)
    {

    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.ConfigurePermissionManagement();
        modelBuilder.ConfigureSettingManagement();
        modelBuilder.ConfigureAuditLogging();
        modelBuilder.ConfigureIdentity();
        modelBuilder.ConfigureTenantManagement();

        modelBuilder.ConfigureCore();
    }
}

i remember trying to move base.OnModelCreating(modelBuilder); up and down as suggested in other issues but nothing happened

The code is working but what "bothers me" is this

builder.Entity<IdentityUser>().Ignore(x => x.ExtraProperties);
builder.Entity<IdentityUserLogin>().HasKey(x => new { x.UserId, x.LoginProvider });
builder.Entity<IdentityUserRole>().HasKey(x => new { x.UserId, x.RoleId });
builder.Entity<IdentityUserToken>().HasKey(x => new { x.UserId, x.LoginProvider });

samquest avatar Jan 23 '20 00:01 samquest

builder.Ignore<IdentityUser>();

no this does not work i get this

Invalid column name 'NormalizedUserName'. Invalid column name 'AccessFailedCount'. Invalid column name 'LockoutEnabled'. Invalid column name 'LockoutEnd'. Invalid column name 'NormalizedEmail'. Invalid column name 'NormalizedUserName'. Invalid column name 'PasswordHash'. Invalid column name 'SecurityStamp'. Invalid column name 'TwoFactorEnabled'.

it works if i use this

   builder.Entity<IdentityUser>().Ignore(x => x.ExtraProperties);
   builder.Entity<IdentityUserLogin>().HasKey(x => new { x.UserId, x.LoginProvider });
   builder.Entity<IdentityUserRole>().HasKey(x => new { x.UserId, x.RoleId });
   builder.Entity<IdentityUserToken>().HasKey(x => new { x.UserId, x.LoginProvider });

if only someone can confirm this is not bad code smell...

samquest avatar Jan 23 '20 00:01 samquest

  1. Does your module depend on AbpIdentityEntityFrameworkCoreModule?

MyProject.CoreModule.EntityFrameworkCore has reference to Volo.Abp.EntityFrameworkCore (2.0.0) Volo.Abp.IdentityEntityFrameworkCore (2.0.0)

I mean explicitly DependsOn.

builder.Ignore<IdentityUser>();

no this does not work i get this

...

Try to configure the Identity module instead:

builder.ConfigureIdentity();

acjh avatar Jan 23 '20 01:01 acjh

this was it

builder.ConfigureIdentity();

now if identity gets configured inside the core module, i have to remove it from the migrationdb context since it calls the ConfigureCore

samquest avatar Jan 23 '20 09:01 samquest

Does it break when called twice?

acjh avatar Jan 23 '20 11:01 acjh

If you want an entity to be related to AppUser, you should try: https://github.com/abpframework/abp/issues/1414#issuecomment-507395552

gdlcf88 avatar Jan 24 '20 02:01 gdlcf88

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Jul 29 '20 11:07 stale[bot]

I am facing the same issue as the SamQuest.

while everything are in place to make use of this good framework, this particular problem of linking the Appuser to other domain user is creating a lot of problems to me.

My requirements are follows. There are 3 types of users

  1. UserA
  2. UserB
  3. UserC

These three users need to be linked to same AbpUser Table. Something like. One AbpUser has one to one relationship with UserA, UserB and UserC. Right now I am not able to make the three users having reference to Abpuser.

I have the Following classes,

`public class UserA : FullAuditedAggregateRoot { public Guid AppUserId { get; set; }// Foreign key referencing the Appuser

public string DisplayName { get; set; }

// Other code block removed for clarity

}` And Appuser Table like this,

`public class AppUser : FullAuditedAggregateRoot, IUser { public virtual Guid? UserAId { get; set; }

public string UserName { get; set; }

public string Email { get; set; }

// ..... Other code block removed for clarity. }`

`builder.Entity(s => { s.ToTable(FashionAppConsts.DbTablePrefix + "UserAs", FashionAppConsts.DbSchema); s.HasOne().WithMany().HasForeignKey(s => s.AppUserId).IsRequired();

            s.ConfigureByConvention();
        });`

But while running the Migrations, the AppUserA table doesn't have foreign key constraint referring to AppUser.

Any ideas, Please let me know. Your valuable suggestions and input make my life easy. Struggling for the past one week. Thank you.

MohanaRanjan avatar Jan 04 '21 10:01 MohanaRanjan

hi @MohanaRanjan Please create a new issue.

maliming avatar Jan 05 '21 01:01 maliming