0

I have an EF code-first model with a table having several one-to-many relationships with other tables:

public class Note
{
  [Key]
  public Guid Id { get; set; }
  public string NoteText { get; set; }
  public string Author { get; set; }
  public DateTime? CreationDate { get; set; }
}

public class Foo
{
  public Foo()
  {
    Notes = new HashSet<Note>();
  }

  [Key]
  public Guid Id { get; set; }
  public virtual ICollection<Note> Notes { get; set; }
  // other properties ommited...
}

public class Bar
{
  public Bar()
  {
    Notes = new HashSet<Note>();
  }

  [Key]
  public Guid Id { get; set; }
  public virtual ICollection<Note> Notes { get; set; }
  // other properties ommited...
}

As you can see, both Foo and Bar have their own list of Notes, but a Note belongs to either a Foo or a Bar.

When scaffolding the migration, EF creates a foreign key for Foo and Bar in the Notes table, which I think is not correct. I would like, instead, that a link table is created between Foo and Notes and another one between Bar and Notes.

Is there a way to automatically do this? Or do I have to manually create these classes in my code-first implementation?

Julien Poulin
  • 12,737
  • 10
  • 51
  • 76

1 Answers1

0

This has already been answered in this other post! But to save you a little googling, you are getting a one-to-many association, which is correct. you want a many-to-many relationship in your code, so what you will need to do is :

in your Notes class:

public class Note
{
  [Key]
  public Guid Id { get; set; }
  public string NoteText { get; set; }
  public string Author { get; set; }
  public DateTime? CreationDate { get; set; }
  public DateTime? CreationDate { get; set; }
  public virtual ICollection<Foo> Foos { get; set; }
  public virtual ICollection<Bar> Bars { get; set; }
}

Hope this helps

Community
  • 1
  • 1
Toze
  • 53
  • 6
  • I really want a one-to-many relationship since a note belongs to only one Foo (or Bar), and a Foo (or Bar) can have many Notes. Also, I don't need the navigation property from Notes. Do you have another suggestion? – Julien Poulin Dec 20 '12 at 13:32
  • 1
    you can try [this link] (http://weblogs.asp.net/manavi/archive/2011/05/17/associations-in-ef-4-1-code-first-part-6-many-valued-associations.aspx) instead, you will need to use `.WithMany` function or the `.Map` one together with the `EntityTypeConfiguration`. The link has useful information. I haven't seen any way to do this using annotations. – Toze Dec 20 '12 at 16:17