Question

I'm having a strange issue when I try to delete an entity Produto using my repository.

Generic Repository:

public class RepositoryBase<T> : IDisposable, IRepositoryBase<T> where T : ModelBase
{
    /*Other Methods that work perfectly*/

    public virtual int Delete(int id)
    {
        try
        {
            T entity = _dataContext.Set<T>().Find(id);

            _dataContext.Set<T>().Remove(entity);

            return _dataContext.SaveChanges();
        }
        catch(DbEntityValidationException ex)
        {

        }
    }
}

Entity:

public class Produto : ModelBase
{
    public virtual int? CodigoComercial { get; set; }

    [Required]
    [MaxLength(150)]
    public virtual string Nome { get; set; }

    [MaxLength(400)]
    public virtual string Ingredientes { get; set; }

    [Required]
    public virtual CategoriaProduto Categoria { get; set; }

    public Produto()
    {
        Categoria = new CategoriaProduto();
    }
}

public class CategoriaProduto : ModelBase
{
    [Required]
    [MaxLength(150)]
    public virtual string Nome { get; set; }
    [MaxLength(400)]
    public virtual string Descricao { get; set; }
    public virtual CategoriaProduto CategoriaPai { get; set; }
    public virtual IList<OpcaoIngrediente> Opcoes { get; set; }
    public virtual CorCategoriaProdutoEnum  Cor { get; set; }
    public virtual  bool Simples { get; set; }
    [MaxLength(400)]
    public string Imagem { get; set; }

    public CategoriaProduto()
    {
        Opcoes = new List<OpcaoIngrediente>();
    }
}

I found the way to catch the exception, that makes no sense, I try to Delete the Product, but It claims that the CategoriaProduto has the Name empty and It's required. as below:

SaborFit.Data.Model.CategoriaProduto failed validation

  • Nome : The field Nome is required.

I can't figure out the issue. If I try to delete the CategoriaProduto, all goes well.

Was it helpful?

Solution

I don't know why you are using Virtual property for most of fields, This cause to have lazy loading and obviously you'll encounter validation error on Any Operation where you call entire entity like .Find() operand. You must first decide what do you wanna do! Another solution that I don't prefer for you is disabling validation on save changes:

context.Configuration.ValidateOnSaveEnabled = false;
context.SaveChanges();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top