【发布时间】:2018-09-22 13:52:30
【问题描述】:
现在我正在建立一个迷你博客。当用户创建帖子时,我想在帖子表中插入来自 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; }
}
【问题讨论】:
-
如果您使用 CodeFirst 或 BaseFirst,请给我们打电话?会有帮助的。
-
你不需要。
Post表中已经有ApplicationUser。例如;如果您想查看特定用户的所有帖子,只需致电context.Posts.Where(p => p.User.Id == 5) -
@Cedric 代码优先,
-
@AdamVincent 我同意你的观点,但我想在 Post 表中插入 UserId 作为外键?
-
然后把
public ApplicationUser User { get; set; }改为public int ApplicationUserId { get; set; }.. 我说是因为如果你两者都有,那将是多余的。然后你需要做一些额外的 Fluent API 代码来将外键映射到 User 表。如果您保持原样,EF 会为您完成所有工作,而无需任何额外开销。
标签: entity-framework asp.net-mvc-3 authentication ef-code-first asp.net-identity