Согласно диаграмме ER, показанной на изображении в вашем вопросе, вы можете определить отношения в EF следующим образом:
public class Equipment // model for Equipment table
{
public int EquipmentID { get; set; }
public IEnumerable<string> Item { get; set; }
public virtual ICollection<CarEquipment> CarEquipments { get; set; }
}
public class Car // model for car table
{
public int CarID { get; set; }
public string Brand { get; set; }
public string Model { get; set; }
public int Price { get; set; }
public string Category { get; set; }
public string Description { get; set; }
public int Production { get; set; }
public int Mileage { get; set; }
public byte[] ImageData { get; set; }
public string ImageMimeType { get; set; }
public virtual ICollection<CarEquipment> CarEquipments { get; set; }
}
public class CarEquipment // model for carequipmeHnt table
{
public int CarID { get; set; }
public int EquipmentID { get; set; }
public virtual Car Car { get; set; }
public virtual Equipment Equipment { get; set; }
}
public class EfDbContext : DbContext
{
public DbSet<Car> Cars { get; set; }
public DbSet<Equipment> Equipments { get; set; }
public DbSet<CarEquipment> CarEquipments { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Car>().HasKey(x => x.CarID);
modelBuilder.Entity<CarEquipment>().HasKey(x => new { x.CarID, x.EquipmentID });
modelBuilder.Entity<Equipment>().HasKey(x => x.EquipmentID);
modelBuilder.Entity<CarEquipment>().HasOne(x => x.Equipment).WithMany(x => x.CarEquipments);
modelBuilder.Entity<CarEquipment>().HasOne(x => x.Car).WithMany(x => x.CarEquipments);
}
}
И теперь вы можете получить доступ к CarEquipment вместе с Car следующим образом:
public class EFCarEquipmentRepository : ICarEquipmentRepository
{
private EfDbContext context = new EfDbContext();
public IEnumerable<CarEquipment> CarEquipment
{
get
{
return context.CarEquipments.Include(x => x.Car);
}
}
}
Если вы также хотите получить доступ к оборудованию, просто включите метод, подобный этому,
context.CarEquipments.Include(x => x.Car).Include(x => x.Equipment)
Примечание. Это один из лучших источников, где можно научиться определять отношения в EF Core: MS Do c