简体   繁体   中英

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?

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' (ie 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();
}

Steven K's answer is correct for removing the foreign key entry on the Metal table, however it will not enforce Unique requirement for the Desctiption field. That is not his fault though because, unfortunately, EF Code First does not have a unique constraint annotation yet.

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