Eliya Amanoeel

Eliya Amanoeel

  • NA
  • 11
  • 421

Entity Framework - Db design suggestion

May 26 2023 10:13 AM

I have two models with many-to-many relationship:

public class Person
{
    public int PersonId { get; set; }
    public string Name { get; set;}
    public virtual ICollection<Hobby> Hobbies { get; set; } = new List<Hobby>();
}

and

public class Hobby
{
    public int HobbyId { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Person> Persons { get; set; } = new List<Person>();
}

In other words a person may have several hobbies and a hobby could interest many persons.

Now I have below model which has many-to-many relationship with the Person model:

public class Activity
{
    public int ActivityId { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Person> Persons { get; set; } = new List<Person>();
}

I have setup my Blazor WASM project and I have populated all the tables using EntityFramework Code First. Here is how my data structure in the database looks like:

  1. I have populated the Hobbies table with example data
  2. I have populated the Persons table with example data, and assigned at least one or more hobby from the table above to each person.
  3. I have implemented all CRUD operations for the two above processes and everything works just fine.

Where am I stuck and what am I trying to achieve? I want to create a new activity with persons based on hobbies. Let's say that my Hobbies table contains the following hobbies:

  • Art
  • Sports
  • Photography

And my Persons table contains the following persons:

  • Clara
  • Mathew
  • Jack
  • Rose

I would like to create new activities like below:

Activity
Name Hobby Person
Activity X Art Clara, Mathew
Activity Y Sports Jack, Rose
Activity Z Photography Clara, Rose

The problem is that with my current design of the database, I can't keep track of what specific Hobby was chosen from each Person to create the Activity. I need a way to reflect that in the database.

For instance, if I browse my activity View.razor, the Hobby field in the activity would list all the hobbies and not that specific one I created the activity based upon.

Please feel free to ask for more details as I may have not been sufficiently clear about everything.

Any suggestions?


Answers (1)