Aleruirib
Aleruirib

Reputation: 11

DBUpdateException while saving entities

When i create a new database registration on TratamientoRealizadoPSIG, the function SaveChanges() throws this exception:

An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.

Looking at it, I cannot find the error.

This is the Entity Code:

public partial class TratamientoRealizadoPSIG
{
    [Key, Column(Order = 1)]
    public Int32 Id { get; set; }

    [Required]
    public DateTime FechaRealizacion { get; set; }
    [Required]
    public TimeSpan HoraRealizacion { get; set; }
    public DateTime? FechaRegistro { get; set; }
    public String Comentario { get; set; }
    public String UsuarioRegistro { get; set; }
    public virtual String Nombre { get; set; }
    public virtual String Motivo { get; set; }
    public virtual String Dinamica { get; set; }
    public virtual Boolean Asiste { get; set; }

    [Required]
    [InverseProperty("TratamientoRealizadoPSIG")]
    public virtual Equipo Equipo { get; set; }

    [Required]
    [InverseProperty("TratamientoRealizadoPSIG")]
    public virtual Demanda Demanda { get; set; }

    [Required]
    [InverseProperty("TratamientoRealizadoPSIG")]
    public virtual PoblacionObjetivo PoblacionObjetivo { get; set; }

    [Required]
    [InverseProperty("TratamientoRealizadoPSIG")]
    public virtual ObjetivosGrupales ObjetivosGrupales { get; set; }

This is the ViewModel:

public partial class CreateTratamientoRealizadoPSIGViewModel
{

    // Entity properties
    public Int32 Id { get; set; }
    [Required]
    public DateTime FechaRealizacion { get; set; }
    [Required]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:hh\\:mm\\:ss}")]
    public TimeSpan HoraRealizacion { get; set; }
    public DateTime? FechaRegistro { get; set; }
    public String Comentario { get; set; }
    public String UsuarioRegistro { get; set; }
    public String Nombre { get; set; }
    public String Demanda { get; set; }
    public String Motivo { get; set; }
    public String ObjetivosGrupales { get; set; }
    public String PoblacionObjetivo { get; set; }
    public String Dinamica { get; set; }
    public Boolean Asiste { get; set; }

    [Required]
    [Display(Name = "Demanda")]
    public int? DemandaId { get; set; }
    [Required]
    [Display(Name = "ObjetivosGrupales")]
    public int? ObjetivosGrupalesId { get; set; }
    [Required]
    [Display(Name = "PoblacionObjetivo")]
    public int? PoblacionObjetivoId { get; set; }
    /*
    public int? ResultadoTestId { get; set; }
    [Required]
    [Display(Name="TipoDeTest")]
    public int? TipoDeTestId { get; set; }
     * */
    [Required]
    [Display(Name="Equipo")]
    public int? EquipoId { get; set; }
    public string IdentityDescription { get; set; }
    public Boolean? isCreateBack { get; set; }
    public string CreateBackUrl { get; set; }
    // DropDownList
    public List<Demanda> DemandaList { get; set; }
    public List<ObjetivosGrupales> ObjetivosGrupalesList { get; set; }
    public List<PoblacionObjetivo> PoblacionObjetivoList { get; set; }
    public List<Equipo> EquipoList { get; set; }
}

And finally the secuence of methods executed:

 [AcceptVerbs(HttpVerbs.Post)]
    public override ActionResult AddTratamientoRealizadoPSIG(int masterId, CreateTratamientoRealizadoPSIGViewModel tratamientoRealizadoPSIGModel)
    {
        if (ModelState.IsValid)
        {
            TratamientoRealizadoPSIG tratamientoRealizadoPSIG = new TratamientoRealizadoPSIG();
            AutoMapper.Mapper.Map<CreateTratamientoRealizadoPSIGViewModel, TratamientoRealizadoPSIG>(tratamientoRealizadoPSIGModel, tratamientoRealizadoPSIG);

            Equipo equipo = _equipoService.Find(tratamientoRealizadoPSIG.Equipo.Id);
            **_equipoService.AddTratamientoRealizadoPSIG(equipo, tratamientoRealizadoPSIG, AuthenticatedUser);**

            return RedirectToAction("Edit", "Equipo", new { id = masterId });
        }
        else
        {
            List<Demanda> allDemanda = _demandaService.FindAll();
            List<ObjetivosGrupales> allObjetivosGrupales = _objetivosGrupalesService.FindAll();
            List<PoblacionObjetivo> allPoblacionObjetivo = _poblacionObjetivoService.FindAll();
            tratamientoRealizadoPSIGModel.DemandaList = allDemanda;
            tratamientoRealizadoPSIGModel.ObjetivosGrupalesList = allObjetivosGrupales;
            tratamientoRealizadoPSIGModel.PoblacionObjetivoList = allPoblacionObjetivo;
            ViewBag.MasterProperty = "Equipo";
            ViewBag.MasterId = masterId;
            ViewBag.Name = "AddTratamientoRealziadoPSIG";
            tratamientoRealizadoPSIGModel.isCreateBack = true;
            tratamientoRealizadoPSIGModel.CreateBackUrl = "~/Equipo/Edit/" + masterId;

            return View("~/Views/TratamientoRealizadoPSIG/Create.cshtml", tratamientoRealizadoPSIGModel);
        }
    }

public void AddTratamientoRealizadoPSIG(Equipo equipo, TratamientoRealizadoPSIG tratamiento, Usuario usuario)
    {
        tratamiento.UsuarioRegistro = usuario.IdentityDescription;
        **base.AddTratamientoRealizadoPSIG(equipo, tratamiento);**
    }

 public virtual void AddTratamientoRealizadoPSIG(Equipo equipo, TratamientoRealizadoPSIG tratamientoRealizadoPSIG)
    {
        equipo = EntitiesDB.EquipoSet.Find(equipo.Id);
        tratamientoRealizadoPSIG.Equipo = equipo;
        equipo.TratamientoRealizadoPSIG.Add(tratamientoRealizadoPSIG);
        tratamientoRealizadoPSIG.Demanda = EntitiesDB.EntryWithState(tratamientoRealizadoPSIG.Demanda, EntityState.Unchanged);
        tratamientoRealizadoPSIG.PoblacionObjetivo = EntitiesDB.EntryWithState(tratamientoRealizadoPSIG.PoblacionObjetivo, EntityState.Unchanged);
        tratamientoRealizadoPSIG.ObjetivosGrupales = EntitiesDB.EntryWithState(tratamientoRealizadoPSIG.ObjetivosGrupales, EntityState.Unchanged);
        **Change(equipo);**
    }

public virtual void Change(Equipo equipo)
    {
        EntitiesDB.Entry(equipo).State = EntityState.Modified;

        **EntitiesDB.SaveChanges();**
    }

SaveChanges() throws the exception. The relations of the database are created correctly. Can someone help me?

Regards.

Upvotes: 0

Views: 2256

Answers (1)

Aleruirib
Aleruirib

Reputation: 11

The problem was not in the relationships between entities in the source code is defined themselves, was in the database itself. Not indicate that the Id was to be increased, a silly mistake ... but error after all. The solution:

  • Open your table in Design
  • Select your column and go to Column Properties
  • Under Indentity Specification, set (Is Identity) = Yes and
    Indentity Increment = 1

I saw this possible solution in the following post Why is SQL server throwing this error: Cannot insert the value NULL into column 'id'?, I tried what was said and problem solved.

Upvotes: 1

Related Questions