Search code examples
asp.net-mvcentity-frameworkdata-annotationsforeign-key-relationshipef-fluent-api

How to relate model property to same model in ASP.NET MVC?


Sometimes, you want to store who registered or created a user account. It's either the user registered himself/herself or some other user account registered him, such as Admin accounts. So, the User table would something like:

public class User : Identity
{
    public int Id { get; set; }
    public string UserName { get; set; }
    public string Email { get; set; }
    public string Name { get; set; }
    // this is the part that I'd to relate to the same model
    [ForeignKey("Id")]
    public virtual User RegisteredBy { get; set; }
}

Using data annotations or Fluent API, how would you relate the User.RegisteredBy to User.Id?

Thanks in advance!


Solution

  • Something like in your class

    public class User : Identity
    {
        public int Id { get; set; }
        public string UserName { get; set; }
        public string Email { get; set; }
        public string Name { get; set; }
    
        // this is the self referential part
        public int? RegisteredById  { get; set; }
        public virtual User RegisteredBy { get; set; }
        public virtual ICollection<User> RegisteredUsers { get; set; }
    }
    

    and then in your DbContext

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>()
            .HasOptional(x => x.RegisteredBy)
            .WithMany(x => x.RegisteredUsers)
            .HasForeignKey(x => x.RegisteredById);
    }
    

    This is untested, but I did something similar in a project a little while ago and it worked fine.