0

I am trying to do a similar thing to what this previous answer had here: How to declare one to one relationship using Entity Framework 4 Code First (POCO)

The problem is, im very new to this and am using Entity Framework 5 code first and the HasConstraint doesnt exist anymore, not to mention Im not good at lamda. I was wondering if anyone could help expand on this so I can map a User class to a Profile class effectively and easily? I need to know how to do this for the configuration files and model builder

Each user has one profile

Also, another quick question, say the profile model had Lists in this, how would I put these effectively in the model builder and configuration files?

Thank you

Community
  • 1
  • 1
user1290653
  • 775
  • 3
  • 11
  • 23

2 Answers2

0

e.g.

public class User
{
    public int Id { get; set; }
    public string Username { get; set; }
    public Profile Profile { get; set; }
    // public int ProfileId { get; set; }
}

public class Profile
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string PostalCode { get; set; }
}
// ...
modelBuilder.Entity<User>()
    .HasOptional(x => x.Profile)
    .WithRequired();

ProfileId is useless, FK is on the 'other side of the fence' (in Profile).
(this makes most sense IMO)

If you do need an Id in User (e.g. to be able to fill in Profile just by its ID when adding User - which if one-to-one is not really used - as you create both profile and user), then you can reverse...

modelBuilder.Entity<User>()
    .HasRequired(x => x.Profile)
    .WithOptional();

...and your ProfileId is actually in the Id (pk -> pk).

NSGaga-mostly-inactive
  • 14,052
  • 3
  • 41
  • 51
0

That solution worked for me

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
 modelBuilder.Entity<ApplicationUser>(entity =>
            {
                entity.HasKey(e => e.Id);
                entity.Property(e => e.Id).HasMaxLength(450);
                entity.HasOne(d => d.Profile).WithOne(p => p.User);
            });


 modelBuilder.Entity<UserProfile>(entity =>
            {
                entity.HasKey(e => e.Id);
                entity.Property(e => e.Id).HasMaxLength(450);
                entity.Property(e => e.Type)
                    .HasMaxLength(10)
                    .HasColumnType("nchar");
                entity.HasOne(d => d.User).WithOne(p => p.Profile);
            });

 }
Angelos
  • 29
  • 3