I'm trying to include items in a property of type list but I'm not able to include the records in the database.
Firstly I have the following class models:
public class Frota
{
public Frota() {
Veiculos = new List<Veiculos>();
}
public string Id { get; set; }
public virutal ICollection<Veiculo> Veiculos { get; set; }
}
public class Veiculo
{
public string Id { get; set; }
public string Nome { get; set; }
}
Mapping:
public class FrotaMap : EntityTypeConfiguration<Frota>
{
...
HasMany(x => x.Veiculos)
.WithMany()
.Map(x =>
{
x.MapLeftKey("FrotaId");
x.MapRightKey("VeiculoId");
x.ToTable("FrotaVeiculos");
});
}
I run a two-step process where I create a Batch and then add the vehicles:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include="...")] FrotaViewModel model)
{
if (ModelState.IsValid)
{
var frota = await Context.Frotas
.Include(x => x.Veiculos)
.SingleOrDefault(x => x.Id == model.Id);
foreach (var veiculo in frota.Veiculos)
frota.Veiculos.Remove(veiculo);
frota.Veiculos.Clear();
foreach (var veiculo in model.Veiculos)
frota.Veiculos.Add(veiculo);
Context.Entry(frota).State = EntityState.Modified;
await Context.SaveChangesAsync();
}
return RedirectToAction("Edit", new { id = model.Id })
}
But Veiculos
is not added to the database and I can not understand why.
What is missing or wrong in this code?