How Do I Add Navigation Properties Between IdentityUser and Custom Tables?

PostAlmostAnything 1 Reputation point
2021-08-06T04:24:32.557+00:00

I have an application using the default IdentityUser for authentication and I need to enable navigation between custom tables and the AspNetUsers table created by Identity. This is necessary to retrieve the UserName of post authors and message senders/recipients . The posts table has a field for UserId which of course matches the corresponding field in the AspNetUsers table. Normally I use navigation properties that were created when my database was scaffolded, but when I installed Identity no models for the Identity tables were created in my Models folder, so I'm not sure what to do.

I had been using the FindByIdAsync followed by GetUserNameAsync functions of the UserManager whenever I needed to get the UserName, but that has run into limits because I need to make the UserName available in json output in controllers, but when I try to use those functions I get a possible memory leak error if there are more than one UserId in a row. That is the case for my Messages table which has UserId columns for Sender and Recipient.

Developer technologies | ASP.NET | ASP.NET Core
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Chao Deng-MSFT 801 Reputation points
    2021-08-06T07:42:10.82+00:00

    Hi @PostAlmostAnything ,
    For example, I have an ASPNetUsers table that I want to associate with the Notifications table and establish a one-to-many relationship with it. So in my ApplicationUser class inside IdentityModels.cs i have

    public virtual ICollection<Notification> Notifications { get; set; }  
    

    My Notifications class has the reverse

    public virtual ApplicationUser ApplicationUser { get; set; }  
    

    By default EF will then create a cascade delete from Notification to AspNetUsers which i dont want - so i also have this in my Context class.

    modelBuilder.Entity<Notification>()  
        .HasRequired(n => n.ApplicationUser)  
        .WithMany(a => a.Notifications)  
        .HasForeignKey(n => n.ApplicationUserId)  
        .WillCascadeOnDelete(false);  
    

    Just remember the definition for AspNetUSers is extended in the ApplicationUser class inside IdentityModels.cs that is generated for you by visual studios scaffolding. Then treat it as any other class/table in your app

    UPDATE - here are examples of full models

    public class ApplicationUser : IdentityUser  
    {  
    
        [StringLength(250, ErrorMessage = "About is limited to 250 characters in length.")]  
        public string About { get; set; }  
    
        [StringLength(250, ErrorMessage = "Name is limited to 250 characters in length.", MinimumLength=3)]  
        public string Name { get; set; }  
    
        public DateTime DateRegistered { get; set; }  
        public string ImageUrl { get; set; }  
    
        public virtual ICollection<Notification> Notifications { get; set; }  
    
        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 class Notification  
    {  
        public int ID { get; set; }  
    
        public int? CommentId { get; set; }  
    
        public string ApplicationUserId { get; set; }  
    
        public DateTime DateTime { get; set; }  
    
        public bool Viewed { get; set; }  
    
        public virtual ApplicationUser ApplicationUser { get; set; }  
    
        public virtual Comment Comment { get; set; }  
    
    }  
    

    All of this is based on the fact that you first use the code to migrate, otherwise the changes to the model will not be reflected in the database.
    For more information, please refer to the official document:
    1.https://learn.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-simple-key%2Csimple-key
    2.Creating a relation with ASPNetUsers table and custom


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best Regards,

    ChaoDeng

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.