One-to-one relationship in CF Entity Framework using mapping

天涯浪子 提交于 2019-12-06 02:37:06
Zafar

I had to modify the UserMap class as follows

public UserMap() {
    this.Property(t => t.Email)
        .IsRequired()
        .HasMaxLength(100);
    this.Property(t => t.Password)
        .IsRequired()
        .HasMaxLength(15);
    this.Property(t => t.Username)
        .IsRequired()
        .HasMaxLength(15);
    this.HasOptional(t => t.UserProfile)
        .WithRequired(t => t.User);
}

It essentially says: "User has an optional entity UserProfile which in turn has a required User entity"

The definition of the key in UserProfile is a must here.

Just looked at it again, do you need to add HasKey to UserMap so it knows which one is the key otherwise you could do the following :-

Are you able to change UserProfile to inherit from User and then add this to your OnModelCreating method

modelBuilder.Entity().ToTable("UserProfile");

this will create your one to one relationship on the database. I had to do this with my current model to get one to one otherwise if you do not specify the ToTable part it will lump them into one table with a Discriminator column

cheers Mark

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!