简体   繁体   中英

Entity Framework Creates unwanted relationship between abstract and derived tables

Using code first, I have some abstract classes and some classes derived from those abstracted classes.

// Abstracted Classes
public abstract class Brand
{
  [Key]
  public int Id { get; set; }
  public string Name { get; set; }
}

public abstract class Model
{
  [Key]
  public int Id { get; set; }
  public string Name { get; set; }

}

// Derived Classes
[Table("ComparisonBrand")]
public class ComparisonBrand : Brand
{
  public ComparisonBrand()
  {
    ComparisonValues = new List<ComparisonValue>();
    Models = new List<ComparisonModel>();
  }

  public virtual ICollection<ComparisonValue> ComparisonValues { get; set; }
  public virtual ICollection<ComparisonModel> Models { get; set; }
}

[Table("ComparisonModel")]
public class ComparisonModel : Model
{
  public int? BrandId { get; set; }
  public int? LogoId { get; set; }

  [ForeignKey("BrandId")]
  public virtual ComparisonBrand ComparisonBrand { get; set; }
  [ForeignKey("LogoId")]
  public virtual ComparisonLogo ComparisonBrand { get; set; }

  public virtual ICollection<ComparisonValue> ComparisonValues { get; set; }
}

My issue is that the migration generates foreign keys for:

  • ComparisonModel.Id > Models.Id
  • ComparisonModel.BrandId > Brands.Id
  • ComparisonModel.BrandId > ComparisonBrand.Id

Since ComparisonBrand.Id is a FK to Brands.BrandId, I get an error when deleting a Brand record. If I delete the ComparisonModel.BrandId > ComparisonBrand.Id relationship, however, the delete works fine.

How can I prevent a relationship from being formed between both the abstracted table and the derived table (Brands and ComparisonBrand)?

You are using the virtual keyword this causes Lazy Loading . You are telling EF to generate Foreign keys for them through this feature. Drop the virtual and you will not create the keys any longer

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