Records in Icollection<> navigation property are not being recorded

Asked

Viewed 97 times

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.

  • It was a typo. And thank you for the warning.

  • Your vehicle registration among Frotaviewmodel, is of what type? The vehicles you are adding, already exist in the base?

  • Are the same kind yes, ICollection<Veiculo>. There is no record at the base at this time I am testing. From Frota yes, but not the vehicles!

  • @jpgrassi, by the way, on the table Veiculos there is also, I just can’t record in the relationship table FrotaVeiculos.

  • I’ve tried to get the records of Veiculo bank also to insert into property Veiculos of Frota but it didn’t work either.

  • I decided by doing Context.Frotas.Attach(frota); after the SingleOrDefault. And look who has no extra settings for Context other than Configuration.ProxyCreationEnabled = false and Configuration.LazyLoadingEnabled = false.

  • 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.

Show 3 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.