Entity framework AspNetUsers作为另一个表中的外键
现在我正在建立一个迷你博客。当用户创建帖子时,我想在帖子表中插入AspNetUsers的用户id作为外键 这里是post模型,所以有人能告诉我制作它的步骤吗Entity framework AspNetUsers作为另一个表中的外键,entity-framework,asp.net-mvc-3,authentication,ef-code-first,asp.net-identity,Entity Framework,Asp.net Mvc 3,Authentication,Ef Code First,Asp.net Identity,现在我正在建立一个迷你博客。当用户创建帖子时,我想在帖子表中插入AspNetUsers的用户id作为外键 这里是post模型,所以有人能告诉我制作它的步骤吗 public class Post { [Required] public int Id { get; set; } [Required] public string Title { get; set; } [Required] public string Content { get; set; } [Re
public class Post
{
[Required]
public int Id { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Content { get; set; }
[Required]
public string Path { get; set; }
[Required]
public DateTime PostDate { get; set; }
public ApplicationUser User { get; set; }
public IEnumerable<Comment> Comments { get; set; }
}
公共类职位
{
[必需]
公共int Id{get;set;}
[必需]
公共字符串标题{get;set;}
[必需]
公共字符串内容{get;set;}
[必需]
公共字符串路径{get;set;}
[必需]
public DateTime PostDate{get;set;}
公共应用程序用户{get;set;}
公共IEnumerable注释{get;set;}
}
您必须使用以下代码才能将AspNetUsersId
用作外键。如果不想将AspNetUsersId
设为可空,可以使用[必需]
public AspNetUsers User { get; set; }
[ForeignKey("AspNetUsersId")]
[Required]
public int AspNetUsersId { get; set; }
是的,在Post
表中插入记录时,必须手动设置AspNetUsersId
假设您有类的对象Post
为obj
。因此,如果AspNetUsers
表PK是Id
,则必须在方法中编写以下代码
obj.AspNetUsersId = AspNetUsers.Id;
如果您使用CodeFirst或BaseFirst,请联系我们?这会有帮助的,你不需要。在
Post
表中已经有ApplicationUser
。例如如果您想查看特定用户的所有帖子,只需调用context.Posts.Where(p=>p.user.Id==5)
@Cedric code首先,@AdamVincent我同意您的看法,但我希望在Post表中插入UserId作为外键,然后将其改为public ApplicationUser user user{get;set;
将其更改为public int applicationserid{get;set;}
。我之所以这样说,是因为如果两者都有,那么它将是多余的。然后,您将需要执行一些额外的流畅API代码来将外键映射到用户表。如果保持原样,EF将为您完成所有工作,而不会产生任何额外开销。