Boa noite, pessoal.
Sou iniciante em C# ASP .NET Core e estou enfrentando problemas com a Foreign Key. Preciso popular um combobox com dados de uma tabela do banco de dados.
A seguir está a minha model Seller
using System;
using System.Collections.Generic;
using System.Linq;
namespace SalesWebMvc.Models {
public class Seller {
public int id { get; set; }
public string name { get; set; }
public string email { get; set; }
public double basesalary { get; set; }
public DateTime birthdate { get; set; }
public Department department { get; set; }
public int DepartmentId { get; set; }
public ICollection<SalesRecord> sales { get; set; } = new List<SalesRecord>();
public Seller() {
}
public Seller(int id, string name, string email, double basesalary, DateTime birthdate, Department department) {
this.id = id;
this.name = name;
this.email = email;
this.basesalary = basesalary;
this.birthdate = birthdate;
this.department = department;
}
public void AddSales(SalesRecord sr) {
sales.Add(sr);
}
public void RemoveSales(SalesRecord sr) {
sales.Remove(sr);
}
public double TotalSales(DateTime initial, DateTime final) {
return sales.Where(sr => sr.date >= initial && sr.date <= final).Sum(sr => sr.amount);
}
}
}
A seguir segue minha model de Department:
using System.Collections.Generic;
using System;
using System.Linq;
namespace SalesWebMvc.Models {
public class Department {
public int id { get; set; }
public string nome { get; set; }
public ICollection<Seller> sellers { get; set; } = new List<Seller>();
public Department() {
}
public Department(int id, string name) {
this.id = id;
this.nome = name;
}
public void AddSeller(Seller s) {
sellers.Add(s);
}
public double TotalSales(DateTime initial, DateTime final) {
return sellers.Sum(seller => seller.TotalSales(initial, final));
}
}
}
Na view coloquei assim:
<div class="form-group">
<label asp-for="Seller.DepartmentId" class="control-label"></label>
<select asp-for="Seller.DepartmentId" asp-items="@(new SelectList(Model.Departments,"Id",
"nome"))" class="form-control"></select>
</div>
Dá erro de integridade referencial!
MySqlException: Cannot add or update a child row: a foreign key constraint fails
Eu gostaria de saber qual a forma mais simples de colocar todos os departamentos dentro de um combobox na View.
Obrigado.