Mandatory attribute in Buddy class does not work with Entity Framework 5 and ASP.NET

There is a field in my database that is not null, but may contain an empty string. When I try to save a record using connection.SaveChanges (), I get an exception: "MyField field is required."

I created the 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 error message that was selected, so I know that the Buddy class is working correctly, but apparently the Required attribute is missing.

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

I have done this before, and also the first link below seems to say that it should work, so I'm at a dead end. Can anyone help?

Links (only the first two seem to be directly relevant, but the others may still be useful):

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 create an Entity Framework property NOT NULL, but not required when submitting a form
Data annotation attributes not working using friend class metadata in an MVC application
Validating data with custom attributes (AttributeTargets.Class) in EF friendship classes

+4
source share
2 answers

I am in the same boat here ... I have some examples of your exact behavior that work fine ...

and now one particular field will not behave ...

But, if I left the attribute "Required (AllowEmptyStrings = true)", everything will return to work just fine. Which, I think, is what I'm really looking for, since the attribute in question does not make much sense (required, but allows the user not to respond) .....

For me the question is more, why does it sometimes work, and sometimes not?

But with a mimic, deleting code like code should solve the problem for you.

+1
source

I worked on this, catching the error:

 public static class ExtensionMethods { public static void SaveChangesWithEmptyStrings(this DbContext context) { try { context.SaveChanges(); } catch (DbEntityValidationException ex) { foreach (DbEntityValidationResult result in ex.EntityValidationErrors) foreach (DbValidationError error in result.ValidationErrors) { Type t = result.Entry.Entity.GetType(); PropertyInfo pi = t.GetProperty(error.PropertyName); pi.SetValue(result.Entry.Entity, ""); } context.SaveChanges(); // Try again } } 

}

0
source

All Articles