Say I have a class like so (details omitted for brevity):
public class Address
{
public Address()
{
PostalCode = "";
}
public string PostalCode { get; set; }
}
In the mapping, the postal code is marked as required:
public AddressMap()
{
this.Property(t => t.PostalCode)
.HasColumnName("PostalCode")
.IsRequired()
.HasMaxLength(50);
}
In the database it is defined as follows:
CREATE TABLE [dbo].[Address] (
[PostalCode] VARCHAR (50) NOT NULL DEFAULT ((''))
);
It is initialized in code with a null value for PostalCode:
string pc = null;
var address = New Address()
{
PostalCode = pc
};
When I go to add that address to the dbContext, and save changes, I get a DbEntityValidationException because I'm trying to save a null value for a NOT NULL column.
Is there a way to have entity framework or the database not attempt to save a .IsRequired string column as null but instead save it as an empty string?