Additional property with foreign key list

asp.net-core c# entity-framework-core

Question

I have two classes, Person and Event. Multiple people can sign up for an event and is coded as a foreign key list. My question is what is the correct way of adding an additional variable such as a paid bool or something? I imagine I will have to make a separate class with a foreign key link on both Person and Event but I wanted to make sure there wasn't some fancy way of adding an additional property.

1
1
2/21/2019 9:02:30 PM

Accepted Answer

If Person have many events then i would have structure my person class like below

public class Person
{
    public int Id { get; set; }

    // each person have many events
    public List<EventRelation> Events { get; set; }
}

public class EventRelation
{
    public int Id { get; set; }

    public Events Event { get; set; }

    // Person Id forgen Key
    public int Person_Id { get; set; }

    // Events Id forgen Key
    public int Event_Id { get; set; }
}


public class Events
{
    public int Id { get; set; }

    public string EventType { get; set; }

}
2
2/21/2019 9:27:58 PM

Popular Answer

Yes, you are doing it the right way. Since it's an N to N relationship, it needs a joining entity as you specified. The joining entity would have two primary (foreign key) properties including PersonId and EventId and other optional properties (in your case Paid).

Update:

Regarding looking for a fancy way, the answer is No. When designing a database, you are limited to the data model you are using which is relational data model here. EF and other kinds of ORMs are just tools for communications between the app and database.
However, if you define one foreign key in Person class with the type of Collection<Event> and another in Event class with the type of Collection<Person>, entity framework will automatically create the joining table with the two foreign keys. But it's not what you desire, because you need to add more properties to the joining table.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow