One-to-Many EF Core

Asked

Viewed 406 times

-1

I have 2 classes, Topic and Users.

Basically a user can have several topics but the topic can only have one user (creator).

When trying to create a Migration, the following error occurred:

Unable to determine the Relationship represented by navigation Property 'Topic.Users' of type 'Users'. Either Manually configure the Relationship, or ignore this Property using the '[Notmapped]' attribute or by using 'Entitytypebuilder.Ignore' in 'Onmodelcreating'.

I know Many-to-Many Feature hasn’t been implemented in EF Core 3.0 yet, but what I did wrong to not do the auto-mapping?

    public class Topic : Entity
{
    public Guid Id { get; set; }

    public string Title { get; set; }

    public string Content { get; set; }

    public Users Users { get; set; }

    public CategoryTopic Categories { get; set; }

    public IEnumerable<Answers> Answers { get; set; }

    public int UpVotes { get; set; }

    public DateTime? EditedAt { get; set; }

    public int DownVotes { get; set; }

    public bool Closed { get; set; }

    public Users ClosedBy { get; set; }
}

User.Cs

    public class Users : Entity
{
    public enum UsersType { Member, Moderator, Admin }

    public Guid Id { get; set; }

    public string Name { get; set; }

    public string LastName { get; set; }

    public DateTime BirthDate { get; set; }

    public string Photo { get; set; }

    public string Email { get; set; }

    public string Username { get; set; }

    public string Password { get; set; }

    public UsersType UserType { get; set; }

    public DateTime CreatedDate { get; set; }

    public DateTime? BannedUntil { get; set; }

    public int BannedTimes { get; set; }

    public int Reputation { get; set; }

    public IEnumerable<Topic> Topics { get; set; }

    public IEnumerable<Answers> Answers { get; set; }
}
  • I put [Notmapped] in the Users property but it also didn’t work

1 answer

0


I had to do the relationship manually in my Context

protected override void OnModelCreating(ModelBuilder moodelbuilder)
{
    moodelbuilder.Entity<Topic>().HasOne(x => x.CreatedBy);
    moodelbuilder.Entity<Topic>().HasOne(x => x.ClosedBy);
    moodelbuilder.Entity<Users>().HasMany(x => x.Topics);

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.