Creating inheritance users from base asp.net identity user - c#

I have problem in which i would like to create N, two in the example, user objects (e.g. Customer & Supplier) which all inherent from the asp.net IdentityUser object. These object have very different additional data besides the the data from the IdentityUser. I would like to use the IdentityUser user as this gives me a flexible way of taking care of authentication and authorization.
This example has been very stripped down but should supply sufficient information concerning the not being able to create a concrete user (e.g. Customer of Supplier). It seems i need to use the UserManager object as this also takes care of creating for example the password hash and additional security information.
I get presented the following error:
{"Attaching an entity of type 'Supplier' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate."}
Classes which inherent from IdentityUser
public class Customer : IdentityUser
{
public string CustomerProperty { get; set; }
}
public class Supplier : IdentityUser
{
public string SupplierProperty { get; set; }
}
Database context class
public class ApplicationDbContext : IdentityDbContext {
public ApplicationDbContext() : base("ApplicationDbContext")
{
Database.SetInitializer(new ApplicationDbInitializer());
}
public DbSet<Customer> CustomerCollection { get; set; }
public DbSet<Supplier> SupplierCollection { get; set; }
}
Seeding class which throws the exception
public class ApplicationDbInitializer : DropCreateDatabaseAlways<ApplicationDbContext>
{
protected override void Seed(ApplicationDbContext context)
{
var userStore = new UserStore(context);
var userManager = new UserManager(userStore);
// Seed customer user which inherents from asp.net IdentityUser
var user = userManager.FindByEmail("customer#customer.com");
if (user == null)
{
user = new User()
{
UserName = "customer#customer.com",
Email = "customer#customer.com"
};
userManager.Create(user, userPassword);
var customerUser = new Customer()
{
Id = user.Id,
CustomerProperty = "Additional Info"
};
context.Entry(customerUser).State = EntityState.Modified;
context.SaveChanges();
}
// Seed supplier user which inherents from asp.net IdentityUser
var user = userManager.FindByEmail("supplier#supplier.com");
if (user == null)
{
user = new User()
{
UserName = "supplier#supplier.com",
Email = "supplier#supplier.com"
};
userManager.Create(user, userPassword);
var supplierUser = new Supplier()
{
Id = user.Id,
IBAN = "212323424342234",
Relationship = "OK"
};
context.Entry(supplierUser).State = EntityState.Modified;
context.SaveChanges();
}
}
}
**** UPDATE ****
The solution below works but i am still struggling with two issues:
I would always like to have one user type (e.g. Customer of Supplier) associated with the IdentityUser. I though about using an interface but this doesn't work.
If i also add the virtual reference towards the IdentityUser on the user types i get an 'Unable to determine the principal end of an association between the types 'ApplicaitonUser' and 'Supplier'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.' exception.
Classes
public class Customer
{
[Key]
public int CustomerId { get;set; }
public string CustomerProperty { get; set; }
*public virtual User User { get; set; }*
}
public class Supplier
{
[Key]
public int SupplierId { get;set; }
public string SupplierProperty { get; set; }
*public virtual User User { get; set; }*
}
**Class IdentityUser (which works) **
public class User : IdentityUser
{
public virtual Supplier Supplier { get; set; }
public virtual Customer Customer { get; set; }
}
**Class IdentityUser (what i would like) **
public class User : IdentityUser
{
public virtual IConcreteUser ConcreteUser{ get; set; }
}
Database context class
public class ApplicationDbContext : IdentityDbContext {
public ApplicationDbContext() : base("ApplicationDbContext")
{
Database.SetInitializer(new ApplicationDbInitializer());
}
public DbSet<Customer> CustomerCollection { get; set; }
public DbSet<Supplier> SupplierCollection { get; set; }
}
**Seeding class **
public class ApplicationDbInitializer : DropCreateDatabaseAlways<ApplicationDbContext>
{
protected override void Seed(ApplicationDbContext context)
{
var userStore = new UserStore(context);
var userManager = new UserManager(userStore);
var roleManager = new RoleManager(roleStore);
var user = userManager.FindByEmail("customer#customer.com");
if (user == null)
{
user = new ApplicationUser()
{
UserName = "customer#customer.com",
Email = "customer#customer.com"
Customer = new Customer()
{
CustomerProperty = "Additional Info"
}
};
userManager.Create(user, userPassword);
roleManager.AddUserToRole("Customer");
}
user = userManager.FindByEmail("supplier#supplier.com");
if (user == null)
{
user = new ApplicationUser()
{
UserName = "supplier#supplier.com",
Email = "supplier#supplier.com",
Supplier = new Supplier()
{
IBAN = "212323424342234",
Relationship = "OK"
}
};
userManager.Create(user, userPassword);
roleManager.AddUserToRole("Supplier");
}
}
}

As others do too I think this is a design problem. There are some alternative approaches like:
use roles to define the "user-type" (a user can be supplier AND customer)
make the Supplier and Customer entities a relation not extension of the user
e.g.:
public class ApplicationUser : IdentityUser
{
public virtual Customer Customer { get; set; }
public virtual Supplier Supplier { get; set; }
}
public class Customer
{
[Key]
public int Id { get; set; }
public virtual ApplicationUser User { get; set; }
public string CustomerProperty { get; set; }
}
public class Supplier
{
[Key]
public int Id { get; set; }
public virtual ApplicationUser User { get; set; }
public string SupplierProperty { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<Customer> Customers { get; set; }
public DbSet<Supplier> Suppliers { get; set; }
}
public class ApplicationDbInitializer
: DropCreateDatabaseAlways<ApplicationDbContext>
{
protected override void Seed(ApplicationDbContext context)
{
var userStore = new UserStore(context);
var userManager = new UserManager(userStore);
var roleManager = new RoleManager(roleStore);
var user = userManager.FindByEmail("customer#customer.com");
if (user == null)
{
user = new ApplicationUser()
{
UserName = "customer#customer.com",
Email = "customer#customer.com"
Customer = new Customer()
{
CustomerProperty = "Additional Info"
}
};
userManager.Create(user, userPassword);
roleManager.AddUserToRole("Customer");
}
user = userManager.FindByEmail("supplier#supplier.com");
if (user == null)
{
user = new ApplicationUser()
{
UserName = "supplier#supplier.com",
Email = "supplier#supplier.com",
Supplier = new Supplier()
{
IBAN = "212323424342234",
Relationship = "OK"
}
};
userManager.Create(user, userPassword);
roleManager.AddUserToRole("Supplier");
}
}
}
and in your logic you can do something like:
if (User.IsInRole("Customer"))
{
// do something
}
DISCLAIMER: This is not a "copy&paste" example and should just give you an idea of a different approach.

I just resolved a similar problem. I created a navigation property of abstract type DomainUser in my AppUser (that inherits from Identity User)
public class AppUser : IdentityUser
{
public DomainUser DomainUser { get; set; }
}
DomainUser looks like this:
public abstract class DomainUser : IAggregateRoot
{
public Guid Id { get; set; }
public AppUser IdentityUser { get; set; }
}
I inherit from DomainUser in all concrete domain user types:
public class AdministrationUser : DomainUser
{
public string SomeAdministrationProperty { get; set; }
}
public class SupplierUser : DomainUser
{
public string SomeSupplierProperty { get; set; }
}
public class Customer : DomainUser
{
public string SomeCustomerProperty { get; set; }
}
And in DbContext in OnModelCreating method I configured Entity Framework to store all entities inherited from DomainUser in separate tables (it's called Table per Concrete Type). And configured one to one relationship between IdentityUser and DomainUser:
modelBuilder.Entity<DomainUser>()
.Map<AdministrationUser>(m =>
{
m.MapInheritedProperties();
m.ToTable("AdministrationUsers");
})
.Map<SupplierUser>(m =>
{
m.MapInheritedProperties();
m.ToTable("SupplierUsers");
})
.Map<Customer>(m =>
{
m.MapInheritedProperties();
m.ToTable("Customers");
});
modelBuilder.Entity<DomainUser>()
.HasRequired(domainUser => domainUser.IdentityUser)
.WithRequiredPrincipal(groomUser => groomUser.DomainUser);
This code added column "DomainUser_Id" to table AspNetUsers and now I'm able to access IdentityUser navigation property in each domain user and DomainUser navigation property in AppUser.

Related

Why does my IdentityUser ICollection property not load on ASP.NET Core 5.0?

I have a many-to-many relationship between AppUser : IdentityUser, and TaxAccount, which is an abstract class that separates into Household and Business. I want to query how many TaxAccounts a User has access to on load.
Here's the AppUser class.
public class AppUser : IdentityUser
{
public string FullName { get; set; }
public virtual List<TaxAccount> Accounts { get; set; }
}
Here's the TaxAccount classes.
public abstract class TaxAccount
{
[Key]
public int ID { get; set; }
[MaxLength(200)]
public string Name { get; set; }
public virtual List<AppUser> Users { get; set; }
}
public class Household : TaxAccount
{
[MaxLength(1000)]
public string HomeAddress { get; set; }
}
public class Business : TaxAccount
{
[EmailAddress, MaxLength(500)]
public string Email { get; set; }
}
However, when I attempt to query the AppUser object in my Razor page, AppUser.Accounts is null! As a result, I always return to the "NoAccount" page.
public async Task<IActionResult> OnGetAsync()
{
AppUser = await _manager.GetUserAsync(User);
// Checks how many TaxAccounts the user has.
if (AppUser.Accounts == null)
{
return RedirectToPage("NoAccount");
}
else if (AppUser.Accounts.Count == 1)
{
return RedirectToPage("Account", new { accountID = AppUser.Accounts[0].ID });
}
else
{
return Page();
}
}
I've found that if I use a .Include() statement to manually connect TaxAccounts to AppUsers, the connection sticks! I just have to insert a .ToList() call that goes nowhere. My question is: why do I need this statement?
AppUser = await _manager.GetUserAsync(User);
_context.Users.Include(X => X.Accounts).ToList();
// Now this works!
if (AppUser.Accounts == null)
EDIT: I've tested removing virtual to see if it was a lazy loading thing, there's no difference.

Seeding data using EF

I'm trying to create an ApplicationUser which has a User as a child object, this is what the models look like:
ApplicationUser:
public class ApplicationUser : IdentityUser
{
public User User { get; set; }
}
User:
public class User
{
public int Id { get; set; }
[ForeignKey("AspNetUser")]
public string AspNetUserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ApplicationUser AspNetUser { get; set; }
}
Within my DbContext I have:
public class IdentityDbContext : IdentityDbContext<ApplicationUser>
{
public IdentityDbContext(DbContextOptions<IdentityDbContext> options)
: base(options)
{
}
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.ApplyConfiguration(new AdminConfiguration());
}
}
AdminConfiguration:
public class AdminConfiguration : IEntityTypeConfiguration<ApplicationUser>
{
public void Configure(EntityTypeBuilder<ApplicationUser> builder)
{
var id = "bc62cdff-77ca-4473-a467-210eb36fdd5d";
var admin = new ApplicationUser
{
Id = id,
UserName = "admin",
NormalizedUserName = "ADMIN",
Email = "admin#dotvvm.com",
NormalizedEmail = "ADMIN#DOTVVM.COM",
EmailConfirmed = true,
SecurityStamp = new Guid().ToString("D")
};
admin.PasswordHash = GeneratePassword(admin, "Admin12345!");
builder.HasData(admin);
builder.OwnsOne(a => a.User).HasData(new User
{
Id = 1,
AspNetUserId = id,
FirstName = "Test",
LastName = "Test"
});
}
private string GeneratePassword(ApplicationUser user, string password)
{
var passHash = new PasswordHasher<ApplicationUser>();
return passHash.HashPassword(user, password);
}
}
With this code, I create a migration and try to execute Update-Database but I get this error:
To change the IDENTITY property of a column, the column needs to be dropped and recreated
I can't figure out what I'm doing wrong, does anyone know?
I'm almost sure that you're using .OwnsOne wrong (but i doubt it is root cause, i speak about it later)
Owned types are Value objects. Value objects have no identity on their own and exist only as a part of their owner like
//this is entity, it has identity
public class Person
{
public Guid Id { get; set; }
public Name Name { get; set; }
}
//and this is value object and could be owned type
public class Name
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
If you want both ApplicationUser and User to be entities (make sense) you could consider One-to-One relationship betwen them, like this
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ApplicationUser>()
.HasOne(a => a.User)
.WithOne(b => b.ApplicationUser)
.HasForeignKey<ApplicationUser>(b => b.AspNetUserId);
}
and then your
builder.HasData(new User
{
Id = 1,
AspNetUserId = id,
FirstName = "Test",
LastName = "Test"
});
might be valid and ... might not
because another possible source of you problem could be Autoincrement Id field (is it autoincrement in your User class?)
If so -
builder.OwnsOne(a => a.User).HasData(new User
{
Id = 1, //<<---- try removing this
AspNetUserId = id,
FirstName = "Test",
LastName = "Test"
});
this could solve your issue

ASP.NET Identity my schema

I already have DB and need to add ASP.NET Identity. My AspNetUser class:
public partial class AspNetUser
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public AspNetUser()
{
AspNetUserClaims = new HashSet<AspNetUserClaim>();
AspNetUserLogins = new HashSet<AspNetUserLogin>();
AspNetRoles = new HashSet<AspNetRole>();
}
public string Id { get; set; }
public string UserName { get; set; }
public string PasswordHash { get; set; }
public string SecurityStamp { get; set; }
public int? CompanyId { get; set; }
public string FullName { get; set; }
[Required]
[StringLength(128)]
public string Discriminator { get; set; }
public string SMSnumber { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<AspNetUserClaim> AspNetUserClaims { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<AspNetUserLogin> AspNetUserLogins { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<AspNetRole> AspNetRoles { get; set; }
}
then my ApplicationDbContext context:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("MainContext", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
connection string:
<add name="MainContext" connectionString="data source=server;initial catalog=3md_maindb_remote;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
ApplicationUser class:
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 int CompanyId { get; set; }
public string SMSnumber { get; set; }
public string FullName { get; set; }
}
ApplicationUserManager:
public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = false
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = false,
RequireDigit = false,
RequireLowercase = false,
RequireUppercase = false,
};
// Configure user lockout defaults
manager.UserLockoutEnabledByDefault = true;
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout = 5;
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug it in here.
manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
{
MessageFormat = "Your security code is {0}"
});
manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
{
Subject = "Security Code",
BodyFormat = "Your security code is {0}"
});
manager.EmailService = new EmailService();
manager.SmsService = new SmsService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider =
new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}
when I try to login, I get an error:
Exception Details: System.Data.SqlClient.SqlException: Invalid column
name 'Email'. Invalid column name 'EmailConfirmed'. Invalid column
name 'PhoneNumber'. Invalid column name 'PhoneNumberConfirmed'.
Invalid column name 'TwoFactorEnabled'. Invalid column name
'LockoutEndDateUtc'. Invalid column name 'LockoutEnabled'. Invalid
column name 'AccessFailedCount'.
Also, I have MainContext:
public partial class MainContext : DbContext
{
public MainContext()
: base("name=MainContext")
{
}
public virtual DbSet<AspNetRole> AspNetRoles { get; set; }
public virtual DbSet<AspNetUserClaim> AspNetUserClaims { get; set; }
public virtual DbSet<AspNetUserLogin> AspNetUserLogins { get; set; }
public virtual DbSet<AspNetUser> AspNetUsers { get; set; }
as I understand, I need to use my MainContext instead of ApplicationDbContext (with my schema) , but don't understand how...
You can use multiple contexts on the same database. Out of the box the Identity Context is set to go. If you don't need to change it then don't. Use the Identity tables for Identity only.
You don't need to define the tables in the Identity Context. Just add the ApplicationDbContext. You can use the same connectionstring as for your MainContext:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("name=MainContext")
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
You really shouldn't add all your tables to the IdentityContext as that is not the place where they should be. Though the tables may be in the same database, the two contexts have nothing to do with eachother.
Keep you own tables in MainContext and do not relate beyond contexts, other than a column where you can reference (value only, not a database reference) the IdentityUser to your MainContext.User. Remove the AspNet... tables from MainContext.
You cannot use the class AspNetUser. So you may as well remove this. Use the ApplicationUser class instead. To overcome the problem of missing fields use this:
public class ApplicationUser : IdentityUser
{
[NotMapped]
public override bool EmailConfirmed { get => base.EmailConfirmed; set => base.EmailConfirmed = value; }
// etc.
}
This will ignore the missing columns. Keep in mind that the properties exist in the code and will have default values. Though I do not think your code is actually going to depend on these properties.
In case the MainContext gives you trouble, you can create your own context using the same entity objects. You can create multiple contexts on the same database, including used tables only, even if you use a seperate assembly.
Since ApplicationDbContext is a DbContext out of the box. You don't need any other DbContext in your project. So simply remove MainContext Class completely in your project and put your own entities in ApplicationDbContext class.
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("MainContext", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
// put your extra entities here like this.
public IDbSet<MyEntity> MyEntites { get; set;}
// don't put Identity related entities like AspNetRoles. Since already added
}

Adding custom field to identitymodel

I have added a new field to MVC's identity model,
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;
}
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int AccountID { get; set; }
public int JeAdmin { get; set; }
public Ekipa Ekipa { get; set; }
}
My ekipa class consists of the following:
public class Ekipa
{
public int id { get; set; }
public string Ime { get; set; }
public int LeaderID { get; set; }
public int Geslo { get; set; }
}
How do I set an object, which I get from database, to the logged in user?
I get the current user,
ApplicationDbContext db = new ApplicationDbContext();
var currentUserId = User.Identity.GetUserId();
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var currentUser = manager.FindById(User.Identity.GetUserId());
EkipaDb db1 = new EkipaDb();
currentUser.Ekipa = db1.Ekipa.Where(m => m.id == 1);
How do I get the object from EkipaDb where id is 1, and add it to the current user?
You can't add an object to a database table's column - but you can add a foreign key.
Add:
public int EkipaId { get; set; }
And make the Ekipa object virtual:
[ForeignKey("EkipaId")]
public virtual Ekipa Ekipa { get; set; }
This will store the Id of the Epika object in the ApplicationUser table, and you can use the navigation property to retrieve the object itself when loading the ApplicationUser.

How can I get result of specified table according to user role in collection using Identity 2.0 .NET MVC

I have one table that represents for example Fruit which has a collection of ApplicationUser. Then in ApplicationUser I add Fruit and FruitId.
So what I need is the result of Fruit which is according to user role of ONE of ApplicationUser in Fruit.
Here is the model.
public class Fruit
{
public int Id { get; set; }
public string Name { get; set; }
public virtual IList<ApplicationUser> User { get; set; }
}
public class ApplicationUser : IdentityUser
{
// some code
public int FruitId { get; set; }
public virtual Fruit Fruit { get; set; }
}
And what I tried is here, but with no success.
var roleManager = new RoleManager<IdentityRole>
(new RoleStore<IdentityRole>(new ApplicationDbContext()));
var role = roleManager.FindByName("Simple");
var SimpleFruits = db.Fruits.Where(f => f.User.FirstOrDefault(u => u.Roles.Select(y => y.RoleId)).Contains(role.Id));

Categories