Search code examples
c#entity-frameworkcode-firstef-code-firstentity-framework-ctp5

Entity Framework CTP5, Code-First. Help creating reference tables via object model


I'm creating new models that I will let EF generate the database for. Models looks like this:

public class Model
{
    public int Id { get; set; }
    public string StyleNumber { get; set; }
    public virtual IList<Metal> Metals { get; set; }
    public virtual IList<ModelImage> Images { get; set; }
}

public class Metal
{
    public int Id { get; set; }
    public string Description { get; set; }
}

I would like Metal to be a reference table w/ the two columns, the "Description" field being unique. Instead, EF creates the Metal table with an additional column referencing the Model Id. Is there a simple way to change the behavior via data annotations or the fluid API?


Solution

  • EF thinks you're having a one-to-many relationship between Model & Metal and the simplest way to model that is by storing the Model ID in the Metal table. If you want to keep the Metal table 'clean' (i.e. no relationship data), then the relationship data must be stored in a seperate table, but by doing that you're also implicitly changing the relationship between Model & Metal. If you really want to go through with this, than you can tell EF that you want a one-way-many-to-many relationship between Model & Metal. You can do that like this inside the DbContext's OnModelCreating function.

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Model>().HasMany(o => o.Metals).WithMany();
    }