Search code examples
c#entity-framework-4savesql-server-ceentity

Avoid Validating an Entity Attribute


Here is one of my Entityclasses:

public class Customer
{
    public int Id { get; set; }
    [Required]
    public int CustomerNumber { get; set; }
    [Required]
    [StringLength(50)]
    public string Prename { get; set; }
    [StringLength(50)]
    public string Surname { get; set; }
    public DateTime? Birthday { get; set; }
    public bool Active { get; set; }
    [Column(TypeName = "image")]
    public byte[] Image { get; set; }
}

After adding objects, I used the following line to save my changes:

((IObjectContextAdapter)context).ObjectContext.SaveChanges();

Everything worked fine, I was able to save a Customer..

Well now I must change that to the following:

context.SaveChanges();

I found out, that my previous line didn't validate, only the second does, because its inheriting from DbContext

Now I have the problem that I cannot save a Customer anymore, the reason is, that I got an exception at the context.SaveChanges(); Line.

In the EntityValidationError I found the following Error: ErrorMessage = "The field Image must be a string or array type with a maximum length of '4000'." Well know my question is, how can I avoid validating this one entity only..? I know that there is a possibilty to avoid validating a whole entity, but thats not the idea. I hope someone can help me, I'm stuck at this one..


Solution

  • You could use a CustomValidationAttribute. Here is an example.

    You could make a method that just returns success.