Error in Edit MVC .NET [closed]

-7

I'm having an error when I edit my profile, my Physical Model is as PartialView , the following error occurs:

Attaching an entity of type 'Projeto.Models.Fisica' failed because another entity of the same type already has the same primary key value

MODEL REGISTRATION

public class Cadastro
{
    public Pessoa Pessoa { get; set; } 
    public Fisica Fisica { get; set; }
}

PHYSICAL MODEL

    public class Fisica : Pessoa
    {
        public string RG { get; set; }
    }

MODEL PESSOA

    public partial class Pessoa
    {
      [Key]
      public int IdPessoa { get; set; }
      public string Nome { get; set; }
    }

VIEW EDIT

    @model CodeFirst.Models.Cadastro
    <div>
       @Html.EditorFor(model => Model.Fisica)
    </div>

PARTIAL VIEW PHYSICS

                    @model CodeFirst.Models.Fisica
                    <div class="col-xs-12 col-md-1-5 marginCimaBaixo">
                        @Html.LabelFor(model => model.RG)
                        @Html.EditorFor(model => model.RG)
                        @Html.ValidationMessageFor(model => model.RG)
                    </div>

CONTROLLER EDIT POST

    public ActionResult Edit(Cadastro cadastro)
    {
       db.Entry(cadastro.Fisica).State = EntityState.Modified;
    }

Thank you.

    
asked by anonymous 15.01.2016 / 16:31

1 answer

6

If Fisica is derived Pessoa , this is not right here:

@model CodeFirst.Models.Fisica
<div>
   @Html.EditorFor(model => Model.Fisica)
</div>

Use @Html.Partial instead of @Html.Editor :

@model CodeFirst.Models.Fisica

<div>
   @Html.Partial("_MinhaPartialPessoaFisica", Model)
</div>

And the Partial :

@Model CodeFirst.Models.Fisica

<div class="col-xs-12 col-md-1-5 marginCimaBaixo">
    @Html.LabelFor(model => model.RG)
    @Html.EditorFor(model => model.RG)
    @Html.ValidationMessageFor(model => model.RG)
</div>

Controller:

public ActionResult Edit(Fisica fisica)
{
   db.Entry(fisica).State = EntityState.Modified;
}

This here is terribly wrong, and it shows that you did not understand how inheritance works:

public class Cadastro
{
    public Pessoa Pessoa { get; set; } 
    public Fisica Fisica { get; set; }
}

If Fisica is derived Pessoa , you do not have to Fisica and Pessoa . In fact, you do not even have this ViewModel Cadastro because as Fisica already derives Pessoa , all Pessoa already exists in Fisica .

So your View Edit should look like this:

@model CodeFirst.Models.Fisica
<div>
   @Html.Partial("_MinhaPartialPessoaFisica", Model)
</div>
    
15.01.2016 / 16:39