One to many relationship with junction table using Entity Framework code first

ef-code-first entity-framework entity-framework-6 one-to-many

Question

I'm having trouble using a junction table to construct a one-to-many relationship while I build a database using EF6 code.

Here is an illustration of what I'm attempting to do:

Foo Entities may include any number (0–n) ofBar entities, thoughBar Entities are not always associated with aFoo I might want one or more of them to also be present in a different sort of entity.Bar therefore, it's crucial thatBar does not include the foreign key of its parent.

The join table would then look like this:

Name        | FooBar
------------|-------
Primary Key | BarID
Key         | FooID

So if we make the entities in the following way:

public class Foo
{
  public long ID { get; set; }
  public ICollection<Bar> Bars { get; set; }
}

public class Bar
{
  public long ID { get; set; }
}

Afterwards, setup them:

public class FooConfiguration : EntityTypeConfiguration<Foo>
{
  HasKey(p => p.ID);
  HasMany(p => p.Bars)
    .WithRequired()
    .Map(m => {
      m.ToTable("FooBar");
      m.MapKey("FooKey");
    });
}

However, this causes the following exception to be thrown:

An exception of type 'System.InvalidOperationException' occurred in mscorlib.dll but was not handled in user code. Additional information: The specified table 'FooBar' was not found in the model. Ensure that the table name has been correctly specified.

I'm not entirely sure what this means, so should I make a separate account?FooBar entity?

How can these entities be set up such that the join table is formed properly?

Thanks!

1
2
10/6/2015 1:15:50 PM

Accepted Answer

ZZZ_tmp
2
10/6/2015 1:25:20 PM

Popular Answer

ZZZ_tmp


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