Asp.NET MVC 5更新导航属性

时间:2019-04-22 15:11:07

标签: c# asp.net-mvc-5 entity-framework-6

我需要更新与主实体关联的实体,但是当我更新它时,仅当我使用调试器时才更改ID,它不会更改导航属性上与之关联的实体...

这是模型

主要实体

public class Parametro
{
    public Parametro()
    {
        AlcanceAbastecimento = 3; // Default Nº PAB
    }

    public int Id { get; set; }       
    public int NumTurnos { get; set; }
    public int NumPAB { get; set; }   
    public int? AlcanceAbastecimento { get; set; }
    public int QtdMin { get; set; }
    public int QtdMax { get; set; }
    public int UAPId { get; set; }

    public UAP UAP { get; set; } // Associated entity
}

public class UAP
{
    public int Id { get; set; }
    public string Nome { get; set; }
    public Parametro Parametro { get; set; }
}

这是一对一的关系

在“编辑”上是视图

@Html.DropDownListFor(model => model.UAPId, (IEnumerable<SelectListItem>)ViewData["UAPS"], "Selecione um UAP", new { @class = "form-control form-control-sm" })

和编辑帖子的控制器

  [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Edit([Bind(Include = "Id,NumTurnos,NumPAB,AlcanceAbastecimento,QtdMin,QtdMax,UAPId")] Parametro parametro)
    {
        if (ModelState.IsValid)
        {
            db.Entry(parametro).State = EntityState.Modified;
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        using (db)
        {
            ViewData["UAPS"] = new SelectList(db.UAP.ToList(), "Id", "Nome");
        }

        return View(parametro);
    }

和流利的api

  protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

            modelBuilder.Entity<UAP>()
                        .HasOptional(u => u.Parametro) /
                        .WithRequired(p => p.UAP); /
        }

此处仅更改UAPId,而不更改实际实体。我想念什么?

0 个答案:

没有答案