2021年2月5日星期五

What type of relationship is this and how should it be configured?

I am trying to create a discussion board using Identity where ApplicationUsers can create, save, hide, and comment on Posts. I was able to get Posts and Comments working without data annotations or overriding OnModelCreating as follows:

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; }      }  

Comment.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; }      }  

But when I extend IdentityUser to add my own custom fields:

public class ApplicationUser : IdentityUser      {          public ICollection<Post> CreatedPosts { get; set; }          public ICollection<Post> SavedPosts { get; set; }          public ICollection<Post> HiddenPosts { get; set; }      }  

Add-Migration returns with error:

"Unable to determine the relationship represented by navigation 'ApplicationUser.CreatedPosts' of type 'ICollection'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'."

Why is EF Core able to determine the relationship between a Post and its Comments but not an ApplicationUser and its created/saved/hidden Posts? I understand that I will have to specify the relationship either by using data annotations or overriding OnModelCreating but I am unsure of how to go about doing this. Any amount of help would be very much appreciated.

https://stackoverflow.com/questions/66072110/what-type-of-relationship-is-this-and-how-should-it-be-configured February 06, 2021 at 07:49AM

没有评论:

发表评论