0

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!

ste-fu
  • 6,879
  • 3
  • 27
  • 46
doncadavona
  • 7,162
  • 9
  • 41
  • 54

2 Answers2

1

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.

ste-fu
  • 6,879
  • 3
  • 27
  • 46
1
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<User>()
                .HasOptional(c => c.RegisteredBy)
                .WithMany()
                .HasForeignKey(c => c.RegisteredById);
}

You can use the above Fluent Api code and your class should look like this

public class User : Identity
{
 public int Id { get; set; }
 public string UserName { get; set; }
 public string Email { get; set; }
 public string Name { get; set; }

 public int? RegisteredById { get; set; }                

 public User RegisteredBy { get; set; }
}
Fred Rogers
  • 413
  • 2
  • 8
  • 19