【发布时间】:2021-05-10 07:36:09
【问题描述】:
我正在尝试使用身份创建一个讨论板,应用程序用户可以在其中创建、保存、隐藏和评论帖子。我能够在没有数据注释或覆盖 OnModelCreating 的情况下使帖子和评论工作,如下所示:
Post.cs:
public class Post
{
public int ID { get; set; }
public string Title { get; set; }
public string Content { get; set; }
[DataType(DataType.DateTime)]
public DateTime CreationDate { get; set; }
public ApplicationUser OriginalPoster { get; set; }
public int Upvotes { get; set; }
public int Downvotes { get; set; }
public int VoteScore { get; set; }
public ICollection<Comment> Comments { get; set; }
}
评论.cs:
public class Comment
{
public int ID { get; set; }
public string Content { get; set; }
public ApplicationUser Commenter { get; set; }
[DataType(DataType.DateTime)]
public DateTime CreationDate { get; set; }
public int Upvotes { get; set; }
public int Downvotes { get; set; }
public int VoteScore { get; set; }
}
ApplicationDbContext.cs:
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Post> Posts { get; set; }
public DbSet<Comment> Comments { get; set; }
}
但是当我扩展 IdentityUser 以添加我自己的自定义字段时:
public class ApplicationUser : IdentityUser
{
public ICollection<Post> CreatedPosts { get; set; }
public ICollection<Post> SavedPosts { get; set; }
public ICollection<Post> HiddenPosts { get; set; }
}
添加迁移返回错误:
"无法确定导航所代表的关系 'ICollection' 类型的'ApplicationUser.CreatedPosts'。任何一个 手动配置关系,或使用 '[NotMapped]' 属性或使用 'EntityTypeBuilder.Ignore' 'OnModelCreating'。”
为什么 EF Core 能够确定帖子与其评论之间的关系,但不能确定 ApplicationUser 与其创建/保存/隐藏的帖子之间的关系?我知道我必须通过使用数据注释或覆盖 OnModelCreating 来指定关系,但我不确定如何去做。任何数量的帮助都将非常感激。
【问题讨论】:
标签: c# entity-framework .net-core entity-framework-core asp.net-identity