0

I have two tables: User and Profile

public class User
{
    public string Id { get; set; }

    public string UserName { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }

    public Profile Profile { get; set; }
}

public class Profile
{
    public string UserName { get; set; }

    public string FirstName { get; set; }
    public string SecondName { get; set; }
    public DateTime Created { get; set; }

    public User User { get; set; }
}

Config part:

public class UserConfiguration : EntityTypeConfiguration<User>
{
    public UserConfiguration()
    {
        ToTable( "Users" );

        HasKey( p => p.Id );

        Property( p => p.UserName ).HasMaxLength( 100 );

        Property( p => p.UserName ).HasColumnAnnotation( "Index",
            new IndexAnnotation( new IndexAttribute( "IX_UserName" )
            {
                IsUnique = true
            } ) ).IsRequired();

        // Add code here to relate to Profile table and what code?
        ...
    }
}

public class ProfileConfiguration : EntityTypeConfiguration<Profile>
{
    public ProfileConfiguration()
    {
        ToTable( "Profiles" );

        HasKey( p => p.UserName );

        Property( p => p.FirstName ).HasMaxLength( 100 );
        Property( p => p.SecondName ).HasMaxLength( 100 );
        Property( p => p.Created ).IsRequired();

        // Or add code here to relate to User table and what code?
        ...
    }
}

I need to related two tables of one-to-one. How to assign a primary key as foreign key Profile.UserName that refers to User.UserName, not User.Id How to implement using Fluent API?

Jeroen Heier
  • 3,520
  • 15
  • 31
  • 32
Grigory
  • 1
  • 1
  • 3
  • 1
    Try this `HasRequired(p => p.Profile).WithMany().HasForeignKey(p => p.UserName)` – Shawn Yan Jun 17 '16 at 09:08
  • Look at [this](http://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-first.aspx) page. – Jeroen Heier Jun 17 '16 at 09:17
  • To **Shawn Yan**... not work, when create record `user.Create(model)` get error: '`Validation failed for one or more entities. See 'EntityValidationErrors' property for more details`. May be the reason of `.WithMany().`' – Grigory Jun 17 '16 at 10:36
  • To **Jeroen Heier**... I tried to do it how at this page before, but the `Profile.UserName` gets value of the `User.Id` – Grigory Jun 17 '16 at 10:36

0 Answers0