0

I'm having trouble with a code first entity model and I'm trying to wrap my head around how to fix it.

In a DB-First model I would have the following:

CarModels
ID,
Name

CarFactory
ID
Name

CarFactoryModels
CarFactoryID
CarModelID

Now... I tried doing this in EF6 with a code-first and my classes are:

public class CarModel
{
public int CarModelId {get;set;}
public string Name {get;set;}
}

public class CarFactory
{
public int CarFactoryId {get;set;}
public string Name { get;set;}
public List<CarModels> ModelsMade {get;set;}
}

When I generate a migration and apply it... the database assumes that each car factory will have a UNIQUE individual and the schema looks like this:

Table Car Models
int ID AutoIncrement
varchar(255) Name
int CarFactoryID REFERENCES CarFactory_ID

Obviously, this is incorrect as the Models are unique to the factory.

Question:

How do I make code-first EF6 recognize the expected schema while continuing to have a reference to the models?

willthiswork89
  • 617
  • 1
  • 4
  • 17
  • 1
    Take a look at [Configure Many-to-Many relationship](http://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx) – Ivan Stoev Jun 09 '17 at 14:30
  • Looks like that might be what i need. I'll try it out and get back to you. Thanks Ivan – willthiswork89 Jun 09 '17 at 15:10

1 Answers1

0

Your CarFactory knows what models it has, but your CarModel doesn't have a reference to their factory.

public class CarModel
{
  public int CarModelId { get; set; }

  public string Name { get; set; }

  public virtual ICollection<CarFactory> CarFactory { get; set; }
}

public class CarFactory
{
  public int CarFactoryId { get; set; }

  public string Name { get; set; }

  public virtual ICollection<CarModel> ModelsMade { get; set; }
}

Notice too how I've made the reference to each other 'virtual'. You have a read about that here

EDIT: I've made it many-to-many as you mentioned the car models can be made at multiple factories

Oyyou
  • 610
  • 5
  • 13
  • but a car model may be made in multiple factories. So i may have two factories with the same car model. So The Model should not have a refertence to the car factory – willthiswork89 Jun 09 '17 at 14:36
  • so even if im never actually referencing the factory from the model i must keep a reference to the factory to get the proper table structure is that correct? – willthiswork89 Jun 09 '17 at 15:42
  • I do believe so, yes. I've been working on something very similar recently, and this is essentially my setup. – Oyyou Jun 09 '17 at 16:39