locked
Access user data via virual lookup Identity core asp.net RRS feed

  • Question

  • User-183185495 posted

    I am using a lookup table which works great for users but ideally I want to link my model back to the AspnetUsers I dont really need a separate table complicating things but the thing is I dont no how I do a lookup back to AspnetUsers as it uses Guids as its id. I am using asp.net core 3.1 and identity and EF Core 3.1.6

    [ForeignKey("StaffMembersOIC1")]
    public int? OIC_1 { get; set; } 
    public virtual StaffMembers StaffMembersOIC1 { get; set; }

    I think the virtual keyword expect and id so when I try it doesnt seem to like it.Can It even access the aspnet user table in this type of way?. The below is what I want to achieved and just to be able to save the user id of the user signed in at that time.

    [ForeignKey("StaffMembersOIC1")]
    public Guid? OIC_1 { get; set; } 
    public virtual ApplicationUser StaffMembersOIC1 { get; set; }

    At present StaffMembers is just this object. I have two fields OIC_1 and OIC_2 which stands for office in charge but it would make more since just to pick this data up from the asp.net identity user table. And use there associated Guids to save into the record.

    public  class StaffMembers {
            public int Id { get; set; }
            public Guid TeannatId { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public int Departments { get; set; }
            public Guid StaffId { get; set; }
            public string CreatedBy { get; set; }
            public bool isActive { get; set; }
            public bool isDeleted { get; set; }
    }

    Monday, July 20, 2020 4:42 AM

All replies

  • User475983607 posted

    Your question is confusing.  Do you want a one-to-one relationship between the User table and the StaffMember table?

    Untested code...

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        //Setup a one-to-one relationship
        modelBuilder.Entity<ApplicationUser>()
            .HasOne(p => p.StaffMembers)
            .WithOne(i => i.User)
            .HasForeignKey<StaffMembers>(b => b.UserForeignKey);
    }  
        
    public class StaffMembers
    {
    
        public int Id { get; set; }
    
        public Guid UserForeignKey { get; set; }
        public ApplicationUser User { get; set; }
    }   
        
        
    public class ApplicationUser : IdentityUser<Guid>
    {
        public StaffMembers StaffMembers { get; set; }
    }

    Reference docs

    https://docs.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-simple-key%2Csimple-key

    Monday, July 20, 2020 11:17 AM