简体   繁体   中英

Code First EF6 strange table layout

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM