EF6 EntityValidationErrors error in filled property

3

I am having a similar problem in two ASP.NET applications with Entity Framework.

When I try to update an entity that already has all the required mandatory attributes I get a EntityValidationErrors exception, however this property that is described in validarion is populated.

The weird thing is that if I put the breakpoint and check the attributes of the object they are all filled and does not cause the error.

In one of the applications I'm getting around this problem by getting the property to receive itself or simply accessing the property and throwing its value into any variable:

ComentariosBlog model = _comentariosBlogNegocios.GetById(idComentatio.Value);

if (model == null)
    return HttpNotFound();

model.Ativo = status.Value;
var teste = model.Publicacao; //<----Contorno
idPost = model.PublicacaoId;
_comentariosBlogNegocios.Salvar(model);

I already have a Try Catch block that handles this error, the problem is that the object has all the required properties filled in and I have to do a "gambi" so that it does not generate errors like this in the above code! The simple fact of accessing the property and playing it in any variable is already in order to give error, but I need a more correct solution to this problem, as I said this is just a "gambi"!

Here are the details of the error that is generated:

Inthisimagewecanseethatthementionedpropertyisalreadyfilled:

Here is the error message inside the try catch:

    
asked by anonymous 14.05.2015 / 19:13

1 answer

2

Your Model is wrong. The navigation property:

public virtual PublicacaoBlog Publicacao { get; set; }

Can not be decorated with [Required] because it will not be saved. The correct is PublicacaoId receive the decoration, because this sim will be saved.

Already completed:

var teste = model.Publicacao; //<----Contorno

It claims the wrong thing in your entire project. It's easy to see around here:

ComentariosBlog model = _comentariosBlogNegocios.GetById(idComentatio.Value);
...
_comentariosBlogNegocios.Salvar(model);
The Entity Framework already implements a repository and it is NOT necessary to implement a layer of "services", "business" or anything, because this is the role of Controller to do . I've written extensively about this for a long time, so I'll mention it again:

There is no point in saying that "MVP has said that it is good practice". No, it's not.

  • Applying DDD in MVC is not good practice;
  • Applying Service layer in MVC project is not good practice;
  • Isolating Controllers and Models in different DLL's is not good practice;

What you do on the line I've marked is to make the dynamic proxy turn an object, which correctly fills the foreign key of the object, and therefore saves it. To resolve, put [Required] in the correct field for it, ie:

[Required]
public int PublicacaoId { get; set; }
    
19.05.2015 / 01:44