2016-09-14 176 views
2

我需要在实体框架中的ApplicationUser和我自己的类之间的1:1关系。实体框架中的1:1关系

我这样做:

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控制台。

无法确定 类型“FinalKaminet.Models.ApplicationUser”和“Models.Posts”之间的关联的主要端。此关联的主体端必须使用 显式配置关系流畅API或数据注释。

我还添加以下代码内IdentityModels,但被示出的另一错误:

ApplicationUser_Post_Target:模型生成过程中检测到

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


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

一个或多个验证错误:多重性是不角色 'ApplicationUser_Post_Target'在'ApplicationUser_Post'关系中有效。 由于从属角色属性不是关键属性,所以从属角色的多重性的上界必须是'*'。

出了什么问题?

+0

显示了什么*另一个错误*? –

+0

@AdilMammadov,已更新的问题。 – Farzaneh

+0

我记得'IdentityUser'有'string'键。这可能是问题吗? –

回答

1

你想在用户和帖子之间建立1对1的关系吗?用户只能发布一个,并且只发布帖子?

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

否则,您处于1对*关系。

+0

正确。它可以使用FK 1对1关联,但是,只有它是单向的。参考:[共享主键关联](http://weblogs.asp.net/manavi/associations-in-ef-4-1-code-first-part-3-shared-primary-key-associations)vs [One一对外关联协会](http://weblogs.asp.net/manavi/associations-in-ef-4-1-code-first-part-5-one-to-one-foreign-key-associations )。 –

0

添加[Required]属性到UserId属性Posts类。

默认情况下,一个字符串属性将可为空,但因为这是外键,你希望被需要的关系,你必须设置UserId属性不为空,可以通过添加[Required]属性来完成。

+0

当我向'UserId'添加'[Required]'时,我得到第二个错误。 – Farzaneh