2016-09-14 147 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