.NET querying Aspnetusers instead of Custom AuthUser and Yet AspNetUser does not Exist - asp.net

I write a custom IdentityUser which is AuthUser.
public class AuthUser : IdentityUser
{
public int StudentsId { get; set; }
public virtual Students StudentProfile { get; set; }
public int InstructorId { get; set; }
public virtual Instructor InstructorProfile { get; set; }
public bool IsStudent { get; set; }
public bool IsInstructor { get; set; }
}
The context is okay as you can see
public class LmsContext : IdentityDbContext<AuthUser> //DbContext
{
}
The startup.cs is all setup
services.AddDbContext<LmsContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("UCIPrimarySchool"))
);
services.AddDefaultIdentity<AuthUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<LmsContext>();
services.AddControllersWithViews();
services.AddRazorPages();
But when I try to login I get the following error.
An unhandled exception occurred while processing the request.
SqlException: Invalid object name 'AspNetUsers'.
Microsoft.Data.SqlClient.SqlCommand+<>c.<ExecuteDbDataReaderAsync>b__169_0(Task<SqlDataReader> result)
Why is is not querying the extended AuthUser but instead goes for the none existing table AspNetUsers?

First, you should clarify your relationship and then migrations and updated the database correctly.
Change your AuthUser like this:
public class AuthUser : IdentityUser
{
public virtual Students StudentProfile { get; set; }
public virtual Instructor InstructorProfile { get; set; }
public bool IsStudent { get; set; }
public bool IsInstructor { get; set; }
}
In your Context:
public DbSet<Students> Students { get; set; }
public DbSet<Instructor> Instructor { get; set; }
Migration and update:
After successfully updating the database, you need to change your View/Shared/_LoginPartial code:
#inject SignInManager<IdentityUser> SignInManager
#inject UserManager<IdentityUser> UserManager
to
#inject SignInManager<AuthUser> SignInManager
#inject UserManager<AuthUser> UserManager
Then
Select your LmsContext Add
Then start your app,and login.

Related

My dbContext return null, when I want get list of user, which are from identity

My dbContext return null, when I want get list of user in Index View. This list are from my database AspNetUsers table, which has been generate by identity. I can get other my database table list.
There is my ApplicationDbContext
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<ProductCategory> ProductCategories { get; set; }
public DbSet<ProductBrand> ProductBrands { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<ApplicationUser> ApplicationUsers { get; set; }
public DbSet<Address> Address { get; set; }
public DbSet<Recipe> Recipes { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<Order_detail> Order_Details { get; set; }
}
There is my UserController
[Area("Admin")]
public class UserController : Controller
{
UserManager<IdentityUser> _userManager;
private ApplicationDbContext _db;
public UserController(UserManager<IdentityUser> userManager, ApplicationDbContext db)
{
_userManager = userManager;
_db = db;
}
public IActionResult Index()
{
return View(_db.ApplicationUsers.ToList());
}
}
There is my ApplicationUser.Model, which inherit IdendityUser
public class ApplicationUser : IdentityUser
{
public string Name { get; set; }
public string Surname { get; set; }
public ICollection<Recipe> Products { get; set; }
public ICollection<Order> Orders { get; set; }
}
I don't know how you register ApplicationDbContext and Identity framework on your ASP.NET Core MVC application because you didn't show them on the question.
There are couple problems in your code.
First, if you have a custom IdentityUser, like the ApplicationUser you have, you would have to use the generic version of IdentityDbContext:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
...
}
You would need to use the matching generic version of IdentityDbContext if you have any of following:
Custom IdentityUser
Custom IdentityRole
Custom primary key
All 7 classes, user and role, plus IdentityUserRole, IdentityUserClaim, IdentityRoleClaim, IdentityUserLogin, and IdentityUserToken
After you register your custom class with IdentityDbContext, you don't need to put the class as one of the DbSet<> there:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
...
public DbSet<ProductCategory> ProductCategories { get; set; }
public DbSet<ProductBrand> ProductBrands { get; set; }
public DbSet<Product> Products { get; set; }
// public DbSet<ApplicationUser> ApplicationUsers { get; set; }
public DbSet<Address> Address { get; set; }
public DbSet<Recipe> Recipes { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<Order_detail> Order_Details { get; set; }
}
You would also need to use the generic version of AddIdentity<TUser>, AddDefaultIdentity<TUser>, or AddIdentityCore<TUser> in your Startup.cs, depending on what you need:
AddDefaultIdentity = AddIdentity + AddDefaultTokens + AddDefaultUI
You didn't specify what version of ASP.NET Core Identity you're using so I don't exactly know which one you use, but the following is how I registered it:
services.AddIdentity<ApplicationUser, ApplicationRole>(options =>
{
options.User.RequireUniqueEmail = ...;
...
})
.AddEntityFrameworkStores<ApplicationDbContext>();
I have all 7 classes customized as well as change the primary key from string to Guid.
Lastly, to use the dependency injected UserManager and SignInManager, you would need to correct generic version of them as well:
[Area("Admin")]
public class UserController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
public UserController(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
public IActionResult Index()
{
// Get the user list
var users = _userManager.Users.ToList();
// Build your view model to define what your UI only needs, not just passing
// everything to it
var vm = new UserManagementListViewModel
{
Users = users.Select(x => new UserViewModel
{
UserId = x.Id,
UserSurname = x.Surname,
ProductCount = x.Products.Count(),
OrderCount = x.Orders.Count()
})
};
return View(vm);
}
}

EF Core 3.1.4 Navigation property returning null in One-To-One relationship

I am having a problem where a navigation property is always returning null in a One-to-One relationship in EF Core 3.1.4.
My models are structured like so:
public class UserCredential
{
public Guid Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public byte[] Salt { get; set; }
public bool IsLocked { get; set; }
public bool IsDeleted { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime? ModifiedDate { get; set; }
public DateTime? DeletedDate { get; set; }
public UserProfile UserProfile { get; set; }
}
public class UserProfile
{
public Guid Id { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string Suffix { get; set; }
public bool IsDeleted { get; set; }
public List<Address> Addresses {get;set;}
public DateTime DOB { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime? ModifiedDate { get; set; }
public DateTime? DeletedDate { get; set; }
public Guid UserCredentialId { get; set; }
public UserCredential UserCredential { get; set; }
}
Based off what I understand, that should have been enough for EF Core to infer the One-To-One relationship. But it didnt work so I defined the relationshup in my dbContext like so:
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<UserProfile>(entity =>
{
entity.HasOne(up => up.UserCredential)
.WithOne(uc => uc.UserProfile)
.HasForeignKey<UserProfile>( up => up.UserCredentialId);
});
}
I checked the db and there is a foreign key from UserProfile -> UserCredentials defined in the table. Likewise both tables have Id as a primary key.
If I post data to a "addUser" endpoint it will be added correctly in the db.
{
"username": "test3",
"password": "password123",
"UserProfile":{
"FirstName": "John",
"LastName": "Doe"
}
}
Db Screenshot
However "UserProfile" in my model is always null.
System.NullReferenceException: 'Object reference not set to an
instance of an object.'
IronCarp.Identity.Models.UserCredential.UserProfile.get returned null.
I'm using a repository to interact with the db and the method that is returning my data/model seems simple enough.
private async Task<UserCredential> GetUserCredentials(string username)
{
return await context.UserCredentials.Where(u => u.Username == username).FirstOrDefaultAsync();
}
Any help is appreciated, I am not sure what I am missing, thanks!
try to include navigation property in linkq, try something like this:
private async Task<UserCredential> GetUserCredentials(string username)
{
return await context.UserCredentials.Include(x => x.UserProfile).Where(u => u.Username == username).FirstOrDefaultAsync();
}
For me this issue was happening intermittently in my integration tests.
It turned out because I was mistakenly registering the EF Core DbContext as Transient and not Scoped:
Services.AddDbContext<SubscriptionsContext>(
options => options.UseNpgsql(appConfig.DatabaseConnectionString,
optionsBuilder => optionsBuilder.EnableRetryOnFailure(3)), ServiceLifetime.Transient);
Should be:
Services.AddDbContext<SubscriptionsContext>(
options => options.UseNpgsql(appConfig.DatabaseConnectionString,
optionsBuilder => optionsBuilder.EnableRetryOnFailure(3)), ServiceLifetime.Scoped);
If you look at the default parameter on the AddDbContext() extension method, it's always Scoped:

How to extend Application User to hold a collection of orders?

I'm trying to extend Application User (using Code-First) to hold a collection of orders, but I'm getting errors.
My Order class is
public class Order
{
public Order()
{
OrderDetails = new HashSet<OrderDetails>();
}
public int ID { get; set; }
public DateTime OrderDate { get; set; }
public string UserId { get; set; }
public bool IsDelivered { get; set; }
public bool IsReturned { get; set; }
public virtual ApplicationUser User { get; set; }
public virtual ICollection<OrderDetails> OrderDetails { get; set; }
}
And I'm trying to extend Application user like this
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 string FirstName { get; set; }
public string LastName { get; set; }
public string CompanyName { get; set; }
public string Profession { get; set; }
public string TaxAuthority { get; set; }
public string TaxNumber { get; set; }
public string Address { get; set; }
public string PostalCode { get; set; }
public string City { get; set; }
public string Region { get; set; }
public string Country { get; set; }
public string Phone { get; set; }
public string MobilePhone { get; set; }
public bool NewsLetterSubscribe { get; set; } = false;
public DateTime TimeStamp { get; set; } = DateTime.Now;
public ICollection<Order> Orders { get; set; }
}
And I'm getting the following errors:
QCMS.Models.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType.
QCMS.Models.IdentityUserRole: : EntityType 'IdentityUserRole' has no key defined. Define the key for this EntityType.
IdentityUserLogins: EntityType: EntitySet 'IdentityUserLogins' is based on type 'IdentityUserLogin' that has no keys defined.
IdentityUserRoles: EntityType: EntitySet 'IdentityUserRoles' is based on type 'IdentityUserRole' that has no keys defined.
Can you please help me to solve this problem?
UPDATE:
I'm using two db contexts. The one provided for Individual User Account (when the project is first created) and a second one named "qvModel" that is for all other database classes of my project.
public partial class qvModel : DbContext
{
public qvModel()
: base("name=qvModel")
{
}
//APPSETTINGS
public virtual DbSet<AdminLog> AdminLog { get; set; }
public virtual DbSet<WebLog> WebLog { get; set; }
//LANGUAGES
public virtual DbSet<Language> Languages { get; set; }
.
.
.
public virtual DbSet<Order> Orders { get; set; }
public virtual DbSet<OrderDetails> OrderDetails { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// Precision attribute for decimals
Precision.ConfigureModelBuilder(modelBuilder);
modelBuilder.Entity<Language>()
.HasMany(e => e.Brochures)
.WithRequired(e => e.Language)
.WillCascadeOnDelete(true);
.
.
.
modelBuilder.Entity<Order>()
.HasMany(c => c.OrderDetails)
.WithRequired(c => c.Order)
.WillCascadeOnDelete(true);
modelBuilder.Entity<ApplicationUser>()
.HasMany(c => c.Orders)
.WithRequired(c => c.User)
.WillCascadeOnDelete(true);
base.OnModelCreating(modelBuilder);
}
}
I found a solution that is very simple.
The solution is to inherit from IdentityDbContext like this
public class qvModel : IdentityDbContext<ApplicationUser>
{
public qvModel()
: base("name=qvModel")
{
}
I was also missing the following line from OnModelCreating
base.OnModelCreating(modelBuilder);
After these changes, my migration is working and I stopped getting the errors I mentioned.

AutoMapper - Cannot map between IdentityUser subclass and its correspondant DTO

I'm working on a project with asp.net core and Identity,
I am trying to create a mapping configuration between IdentityUser subclasse and its correspondant DTO using Automapper
I have done similar configuration with other classes and it works fine, but with IdentityUser subclass it behaves differently :
Here is my IdentityUser subclasse :
public partial class Collaborateur : IdentityUser
{
public Collaborateur() : base()
{
this.Activites = new HashSet<ActiviteCollaborateur>();
this.ActeursAvantVente = new HashSet<ActeurAvv>();
}
public string Nom { get; set; }
public string Prenom { get; set; }
public string Telephone { get; set; }
public Nullable<long> Matricule { get; set; }
public string Structure { get; set; }
public string Login { get; set; }
public RoleEnum Role { get; set; }
public virtual ICollection<ActiviteCollaborateur> Activites { get; set; }
public virtual ICollection<ActeurAvv> ActeursAvantVente { get; set; }
public virtual Agence Agence { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime LastModified { get; set; }
}
Its corresponding DTO :
public class CollaborateurDTO : BaseDTO
{
public string Nom { get; set; }
public string Prenom { get; set; }
public string Telephone { get; set; }
public Nullable<long> Matricule { get; set; }
public string Structure { get; set; }
public string Login { get; set; }
public RoleEnum Role { get; set; }
}
CollaborateurProfile config class :
public class CollaborateurProfile : Profile
{
CollaborateurProfile()
{
CreateMap<Collaborateur, CollaborateurDTO>().ReverseMap();
CreateMap<Collaborateur, Collaborateur>()
.ForMember(x => x.Id, opt => opt.Ignore())
.ForMember(x => x.CreatedAt, opt => opt.Ignore())
.ForMember(x => x.LastModified, opts => opts.MapFrom(src => DateTime.UtcNow));
}
}
and Startup.cs :
services.AddAutoMapper();
it stops at this line with
MissingMethodException was unhandled by user code
An exception of type 'System.MissingMethodException' occurred in System.Private.CoreLib.ni.dll but was not handled in user code
By mistake i answered this question at the question linked in the comments (https://stackoverflow.com/a/46567611/7131186)
Here is my answer:
In my case (and it seems that this is your case too) it was a copy/paste problem. I somehow ended up with a PRIVATE constructor for my mapping profile:
using AutoMapper;
namespace Your.Namespace
{
public class MappingProfile : Profile
{
MappingProfile()
{
CreateMap<Animal, AnimalDto>();
}
}
}
(take note of the missing "public" in front of the ctor)
which compiled perfectly fine, but when AutoMapper tries to instantiate the profile it can't (of course!) find the constructor!

Object Reference not.... At the time of _mscustomerRepository.Insert(customer);

I am working on Nopcommerce 2.40 .I have created new table ,its class and mapping in project
class code
namespace Nop.Core.Domain.Customers
{
public partial class MSCustomer:BaseEntity
{
public virtual string Name { get; set; }
public virtual string Email { get; set; }
public virtual string Address { get; set; }
public virtual string PhoneNumber { get; set; }
public virtual string ComapnyName { get; set; }
public virtual DateTime CreatedOnUtc { get; set; }
}
}
Below is my mapping
public partial class MSCustomerMap : EntityTypeConfiguration<MSCustomer>
{
public MSCustomerMap()
{
this.ToTable("MSCustomer");
this.HasKey(c => c.Id);
this.Property(u => u.Name).HasMaxLength(1000);
this.Property(u => u.Address).HasMaxLength(1000);
this.Property(u => u.Email).HasMaxLength(100);
this.Property(c => c.PhoneNumber).HasMaxLength(100);
this.Property(c => c.CompanyName).HasMaxLength(100);
}
}
public virtual void CreateCustomer(MSCustomer customer)
{
if (customer == null)
throw new ArgumentNullException("cutomer");
_mscustomerRepository.Insert(customer);
//event notification
_eventPublisher.EntityUpdated(customer);
}
I have created "MScustomer" table in database but at the time of insertion its throwing error that "Object reference not set to an instance of an object."
In Controller I am assigning values to property and passing customer class to insert method.
Is there any solutions.
It throws exception at the _mscustomerRepository.Insert(customer);
Thanks In Advance

Resources