3

I'm trying to define a one to many relationship, as well as a one to one relationship between the same 2 entities "UserProfile" and "Blog". I think I have succeeded with the following code, however, it results in creating a new column in "Blog" table called "UserProfile_UserId" (FK). I don't understand why it does this.

The relationships in English are: 1. "A UserProfile has many Blogs" 2. "A UserProfile has one main optional (nullable) Blog"

So ultimately I'd like to see a FK from Blog.UserId to UserProfile.UserId And a nullable FK from UserProfile.BlogId to Blog.Id And I think that is all... I especially don't want additional columns added by EF.

public class UserProfile
{
    [Key]
    public int UserId { get; set; }
    public int? BlogId { get; set; }
    public virtual Blog Blog { get; set; }  // This is a user's main blog
    public virtual ICollection<Blog> AllUsersBlogs { get; set; }
}

public abstract class Blog
{
    [Key]
    public int Id { get; set; }


    public int UserId { get; set; }

    [ForeignKey("UserId")]
    public virtual UserProfile User { get; set; }
}
4

1 に答える 1