0
I’m trying to make an inclusion of items in a list property but I’m not able to include the records in the database.
First 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 the Veiculos
are not added in the database and I cannot understand why.
What is missing or wrong in this code?
Your mapping is between Fleet - Vehicle. In your example code, vc is linking Lots with vehicles. Either you forgot to put the Lot class, or there’s something really wrong.
– jpgrassi
It was a typo. And thank you for the warning.
– JamesTK
Your vehicle registration among Frotaviewmodel, is of what type? The vehicles you are adding, already exist in the base?
– jpgrassi
Are the same kind yes,
ICollection<Veiculo>
. There is no record at the base at this time I am testing. FromFrota
yes, but not the vehicles!– JamesTK
@jpgrassi, by the way, on the table
Veiculos
there is also, I just can’t record in the relationship tableFrotaVeiculos
.– JamesTK
I’ve tried to get the records of
Veiculo
bank also to insert into propertyVeiculos
ofFrota
but it didn’t work either.– JamesTK
I decided by doing
Context.Frotas.Attach(frota);
after theSingleOrDefault
. And look who has no extra settings for Context other thanConfiguration.ProxyCreationEnabled = false
andConfiguration.LazyLoadingEnabled = false
.– JamesTK
I guess you don’t need that Jeep Jeep either. The Frotaveiculos table is created automatically unless you have other custom fields in it. If not, you can take and test.
– jpgrassi