Я создаю приложение, используя ASP.NET Core MVC.Я пытаюсь вставить новую запись с отношением «многие ко многим».У меня есть 3 таблицы Repairs
, Parts
и RepairParts
.
Как вставить RepairId
и PartId
в таблицу RepairParts
?EF Core предоставляет что-то для этого?Я искал документацию, но там ничего не говорится о том, как это сделать.
Делает ли Entity Framework это автоматически?(вставьте в сводную таблицу) Или мне нужно сделать это вручную?Пример может помочь.
Ремонт класс:
public class Repair
{
[Key]
public int RepairId { get; set; }
public int VehicleId { get; set; }
public string Notes { get; set; }
public string Mileage { get; set; }
public DateTime RepairDate { get; set; }
public string uuid { get; set; }
[ForeignKey("VehicleId")]
public Vehicle Vehicle { get; set; }
public virtual ICollection<RepairParts> RepairParts { get; set; }
}
Деталь класс:
public class Part
{
public int PartId { get; set; }
public int Code { get; set; }
public string PartCode { get; set; }
public string Type { get; set; }
public string Name { get; set; }
public string Descr { get; set; }
public string Manufacturer { get; set; }
public string uuid { get; set; }
public virtual ICollection<RepairParts> RepairParts { get; set; }
}
RepairPart класс:
public class RepairParts
{
public int RepairId { get; set; }
public Repair Repair { get; set; }
public int PartId { get; set; }
public Part Part { get; set; }
public decimal price { get; set; }
}
DbContext класс:
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Customer> Customers { get; set; }
public DbSet<TaxOffice> TaxOffices { get; set; }
public DbSet<Vehicle> Vehicles { get; set; }
public DbSet<Part> Parts { get; set; }
public DbSet<Repair> Repairs { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<Customer>()
.HasMany(v => v.Vehicles)
.WithOne(b => b.Customer);
builder.Entity<Vehicle>()
.HasOne(c => c.Customer)
.WithMany(b => b.Vehicles);
builder.Entity<Vehicle>()
.HasMany(v => v.Repairs)
.WithOne(c => c.Vehicle);
builder.Entity<RepairParts>()
.HasKey(t => new { t.RepairId, t.PartId });
builder.Entity<RepairParts>()
.HasOne(r => r.Repair)
.WithMany(t => t.RepairParts)
.HasForeignKey(f => f.RepairId);
builder.Entity<RepairParts>()
.HasOne(r => r.Part)
.WithMany(p => p.RepairParts)
.HasForeignKey(f => f.PartId);
}
}