Entity Framework Code First "join table"

c# ef-code-first ef-migrations entity-framework entity-framework-6

Question

I am working with Entity Framework Code First.

I have an Entity Called Notes

I also have other Entities such as BusinessPartners Opportunities WorkOrders

All of these entities may have notes.

What is the best way to model this

1.) in the notes table have optional foreign keys to Business partners, Opportunities, and workorders. Then just set the optional key to which the note is related

2.) have intermediate tables such as BusinessPartnerNotes, with two field BusinessPartnerId and NoteId

It should be mentioned that a note is never going to be related to two entities at the same time.

Any help or suggestions would be appreciated.

1
0
1/9/2016 9:15:36 PM

Accepted Answer

Given your description of the cardinalities, and assuming Notes for BusinessPartners have the same format of Notes for Opportunities, I'd go with the simplest approach (option 1. in your list).

class Note
{
    public int Id { get; set; }
    public string Content { get; set; }
}
class BusinessPartner
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Note> Notes { get; set; }
}
class Opportunity
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Note> Notes { get; set; }
}

Which should generate the following tables:

Notes
  Id
  Content
  BusinessPartner_Id
  Opportunity_Id
BusinessPartners
  Id
  Name
Opportunities
  Id
  Name
1
1/9/2016 9:57:44 PM


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