有多少额外的外键?

时间:2016-10-10 17:46:37

标签: asp.net asp.net-mvc-4 many-to-many code-first

我想在user和post之间生成一个联结表,我希望在post表中有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; }

这会在post表中生成两个UserId(applicationUser_id和User_id),在User表中生成Post_PostId。我只想在Post表中添加一个额外的字段,FK UserId。

我想要三张这样的表

发表

帖子ID 信息 日期 UserId FK

用户

用户Id 而asp.net身份用户中的其他字段

UserPosts

用户Id 帖子ID

1 个答案:

答案 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)UserId(fk)3)PostId(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)
{


}