Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/drupal/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Entity framework AspNetUsers作为另一个表中的外键_Entity Framework_Asp.net Mvc 3_Authentication_Ef Code First_Asp.net Identity - Fatal编程技术网

Entity framework AspNetUsers作为另一个表中的外键

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

现在我正在建立一个迷你博客。当用户创建帖子时,我想在帖子表中插入AspNetUsers的用户id作为外键 这里是post模型,所以有人能告诉我制作它的步骤吗

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将为您完成所有工作,而不会产生任何额外开销。