ASP.NET Optional 1:1 relationship with ApplicationUser (Identity 2.0)

253 Views Asked by At

I have a Trainee which must connect to an ApplicationUser. The Trainee model has fields that do not relate to the actual user account, but needs to get things like FirstName, LastName from ApplicationUser as a user may not necessarily be a trainee.

However, I get these errors, despite defining my foreign key for the user in Trainee:

One or more validation errors were detected during model generation:

MyApp.Models.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType. MyApp.Models.IdentityUserRole: : EntityType 'IdentityUserRole' has no key defined. Define the key for this EntityType...

...etc etc. Anyway, here's my current architecture:

The Trainee model:

public class Trainee
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public string TraineeId { get; set; }

    // other fields, not relevant
    [ForeignKey("TraineeId")]
    public virtual ApplicationUser User { get; set; }
}

ApplicationUser and context:

    public class ApplicationUser : IdentityUser
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        // other arbitrary fields
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("SARSDbContext")
        {
        }
    }

Data context and model builder:

public class SARSDbContext : DbContext
{
    public DbSet<Trainee> Trainees { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Trainee>()
                    .HasRequired(c => c.User);
    }
}

I looked here and here for info but I didn't find a solution.

0

There are 0 best solutions below