Archive

Posts Tagged ‘one-to-one’

EF4.1 Code-First: One-to-One Foreign Key Associations

September 23, 2011 Leave a comment
public class User
    {
        public Guid UserId { get; set; }
        public int UserProfileId { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
        public string Email { get; set; }
        public DateTime CreatedOn { get; set; }
        public DateTime LastLoginOn { get; set; }
        [ForeignKey("UserProfileId")]
        public UserProfile UserProfile { get; set; }
        public ICollection<Role> Roles { get; set; }
    }

public class UserProfile
    {
        public int UserProfileId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Phone { get; set; }
        public string Mobile { get; set; }
        public byte Status { get; set; }
        public DateTime CreatedOn { get; set; }
        public DateTime UpdatedOn { get; set; }
    }

You get

Alternatively


protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<User>().HasRequired(u => u.UserProfile)
                .WithMany()
                .HasForeignKey(u => u.UserProfileId);
        }
Categories: .NET Tags: , , ,