Programming/Entity Framework

Configure One-to-One Relationship Code First / 1:1 테이블 릴레이션

isna.me 2014. 1. 25. 07:38

// Code Sample

Code first 1 : 1 relationship

public class User

{
        public int Id { get; set; }

        public string UserName { get; set; }

        public DateTime CreatedOnUtc { get; set; }


        public virtual UserProfile UserProfile { get; set; }
}

public class UserProfile
{
        public int Id { get; set; }

        public int UserId { get; set; }

        public string FirstName { get; set; }

        public string LastName { get; set; }


        public virtual User User { get; set; }
}

 

Table mapping

public partial class UserMap : EntityTypeConfiguration<User>
{
        public UserMap()
        {
            this.ToTable("Users");
            this.HasKey(c => c.Id);
        }
}

 

public partial class UserProfileMap : EntityTypeConfiguration<UserProfile>
{
        public UserProfileMap()
        {
            this.ToTable("UserProfiles");
            this.HasKey(c => c.UserId);

            this.HasRequired(t => t.User)
                .WithRequiredDependent(t => t.UserProfile)
                .Map(x => x.MapKey("UserId"))
                .WillCascadeOnDelete(false);
        }
}