Tuesday, April 26, 2011

How to Pass Empty String in Entity Framework

While working with Data Warehouse project, most database columns were designed as required even thought there are no data to populate with. In that situation, an empty string or blank will be used. 

Here is an example: The Note column is required and could be populated with empty string if there is no additional information provided.

image

When using Entity Framework to insert or update this type of field by passing in a blank, we often encounter a “field is required” validation error as below:

image

To overcome this issue, we could add Data Annotations as:

[MetadataType(typeof(Report_META))]
   public partial class Report
   {
   }
   public partial class Report_META
   {
       [Required(AllowEmptyStrings = true)]
       [DisplayFormat(ConvertEmptyStringToNull = false)]
       public object Note { get; set; }
 
    }

When setting AllowEmptyStrings to true for a specific data field, the framework does not perform validation and transforms the empty string to null. This value is then passed to the database.

When setting ConvertEmptyStringToNull  to false, the framework will not automatically convert the empty string value to null when the data field is updated in the database.

After adding the Data Annotations, we could use the blank/empty string to populate or modify the Note field now.





image

3 comments: