1:1 关系 Entity framework

1:1 relationship in Entity framework

我需要 1:1 ApplicationUser 和我在 entity framework 中自己的 class 之间的关系。

我这样做:

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        return userIdentity;
    }

    /*Realations*/

    public virtual ICollection<Comment> Comments { get; set; }
    public virtual Posts Post { get; set; }
}


public class Posts : System.Object
{
    public Posts()
    {
        this.PostDate = DateTime.Now;
        this.PostViews = 0;
        this.PostPic = "d.jpg";
    }

    [Key]
    public int PostID { get; set; }

    public string PostName { get; set; }
    public string PostSummery { get; set; }
    public string PostDesc { get; set; }
    public string PostPic { get; set; }
    public DateTime PostDate { get; set; }
    public int PostViews { get; set; }
    public string postMetaKeys { get; set; }
    public string PostMetaDesc { get; set; }


    public string UserId { get; set; }
    [Key, ForeignKey("UserId")]
    public virtual ApplicationUser ApplicationUser { get; set; }


    public int CategoryID { get; set; }
    [Key, ForeignKey("CategoryID")]
    public virtual Categories Category { get; set; }

    public virtual ICollection<Comment> commnets {get; set;}
}

但是当我在 Nuget 控制台中编写命令 "add-migration relation" 时出现异常。

Unable to determine the principal end of an association between the types 'FinalKaminet.Models.ApplicationUser' and 'Models.Posts'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

我还在 IdentityModels 中添加了以下代码,但显示了另一个错误:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder); 


        modelBuilder.Entity<ApplicationUser>()
        .HasOptional(f => f.Post)
        .WithRequired(s => s.ApplicationUser);
    }

One or more validation errors were detected during model generation:

ApplicationUser_Post_Target: : Multiplicity is not valid in Role 'ApplicationUser_Post_Target' in relationship 'ApplicationUser_Post'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.

怎么了?

[Required] 属性添加到 UserId 属性 in Posts class.

默认情况下,字符串 属性 可以为空,但由于这是外键并且您希望关系为必填项,因此您必须设置 UserId 属性 不可为空,可以通过添加 [Required] 属性来完成。

您想在用户和 post 之间建立一对一的关系吗?一个用户只能 post 一个,而且只能 post ?

无论如何,在 EF(至少 6)中,可以在共享相同 PK 的两个实体之间建立一对一的关系。也就是说PK就是FK。所以必须把posts的PK设置成字符串。

否则你是一对一的关系。