2016-10-10 33 views
0

我想在用戶和帖子之間生成一個聯結表,我想在帖子表中添加userId。多對多有多餘的外鍵?

我有這樣的代碼

public class Post 
{ 
    public Post() 
    { 
     this.ApplicationUser = new HashSet<ApplicationUser>(); 
    } 

    public int PostId { get; set; } 
    public string Message { get; set; } 
    public DateTime MessageDate { get; set; } 

    public virtual ApplicationUser User { get; set; } //this is the problem 

    public virtual ICollection<ApplicationUser> ApplicationUser { get; set; } 
} 

public class ApplicationUser : IdentityUser 
{ 
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) 
    { 
     // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType 
     var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); 
     // Add custom user claims here 
     return userIdentity; 
    } 

    public ApplicationUser() 
    { 
     this.Posts = new HashSet<Post>(); 
    } 

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

我得到額外的接線表和用戶與柱之間的許多一對多的關係。但這是錯誤的。

public virtual ApplicationUser User { get; set; } 

這產生在後表(applicationUser_id和USER_ID)和Post_PostId在用戶表中的兩個用戶ID。我只想在Post表中添加一個額外的字段,FK UserId。

我想三個表這樣

帖子ID 消息 日期 用戶ID FK

用戶

用戶ID 和TH在asp.net用戶身份字段

UserPosts

用戶ID電子其餘 帖子ID

+0

請查看我的更新代碼 –

回答

0

用戶表

public partial class User 
{ 

public User() 
{ 
    this.Posts = new HashSet<Post>(); 
    this.UserPosts = new HashSet<UserPost>(); 
} 

public int UserId { get; set; } 
public string Username { get; set; } 

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

public virtual ICollection<UserPost> UserPosts { get; set; } 
} 

郵政表

public partial class Post 
{ 
public Post() 
{ 
    this.UserPosts = new HashSet<UserPost>(); 
} 

public int PostId { get; set; } 
public string Message { get; set; } 
public Nullable<System.DateTime> Date { get; set; } 
public Nullable<int> UserId { get; set; } 

public virtual User User { get; set; } 

public virtual ICollection<UserPost> UserPosts { get; set; } 
} 

和你的映射表中,像這樣 色譜柱1)ID(PK),2)用戶ID(FK)3)帖子ID(FK)

使用實體框架表有一個主鍵必要的。

UserPost表

public partial class UserPost 
{ 
public int Id { get; set; } 
public Nullable<int> UserId { get; set; } 
public Nullable<int> PostId { get; set; } 

public virtual Post Post { get; set; } 
public virtual User User { get; set; } 
} 

更新的代碼

modelBuilder.Entity<Post>().ToTable("userid table name"); 

此行添加在低於此類的方法ApplicationDbContext

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 


} 
+0

是否明確地必須設置用戶UserPost才能在帖子中獲取外鍵?如果你看看我的代碼,它會生成一個userPost表和多對多的關係,它的工作正常。問題是在發佈表中向asp.net標識用戶添加FK密鑰。可以看到你在帖子類中使用了類似的代碼「公共虛擬用戶用戶{get; set;}」,但它不適合我。 – Xtreme

+0

我的代碼不工作? –

+0

您的代碼有效,但並不完全符合我的要求。您創建一個新的類用戶,但我想使用Applicationuser。當您使用asp.net Identity創建一個新項目時,會自動創建一個用戶表(AspNetUser),我想使用已經生成的表。看到我的第一篇文章。問題是在發佈表中獲取UserId。像公共字符串Id {get;組; } 不管用。 – Xtreme