Search code examples
asp.netentity-framework-5buddy-class

Required attribute in Buddy Class not working with Entity Framework 5 and ASP.NET


My database has a field that is not nullable, but can contain an empty string. When I try to save the record using connection.SaveChanges(), I get an exception saying "The MyField field is required."

I have created a BuddyClass as follows, but I still get the message:

namespace MyNamespace {
[MetadataType(typeof(QuesT_Metadata))] public partial class QuesT { }
public class QuesT_Metadata {
    [Required(AllowEmptyStrings = true)
    public string MyField { get; set; }
}
}

I can use the ErrorMessage attribute to change the message in the error that is thrown, so I know the Buddy Class is working properly, but apparently the Required attribute is not.

I also tried including attribute DisplayFormat(ConvertEmptyStringToNull = false), but got the same result.

I have done this before, and also the first reference below seems to say it should work, so I'm stumped. Can anyone help?

References (Only the first two seem directly relevant, but the others may still be helpful):

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.requiredattribute.allowemptystrings.aspx
http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayformatattribute.convertemptystringtonull.aspx
How to make an Entity Framework property NOT NULL, but not required in form submission
Data annotation attributes not working using buddy class metadata in an MVC app
Data validation with custom attributes (AttributeTargets.Class) on EF buddy classes


Solution

  • I'm in the same boat here... I've got several instances of your exact behavior which are working just fine....

    and now, one particular field won't behave...

    But, if I leave off the "Required(AllowEmptyStrings = true)" attribute, things go back to working just fine. Which, I guess is what I'm really looking for, as the attribute in question doesn't really make all that much sense (Required, but allow the user not to answer).....

    For me the bigger question is why it sometimes works, and sometimes doesn't ?

    But at a miminum, deleting the one like of code should solve the problem for you.