سؤال

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

نصائح أخرى

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top