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?
One option is to change the get accessor of the property to remove null values:
public class Address
{
private string _postalCode;
public Address()
{
PostalCode = "";
}
public string PostalCode
{
get
{
//This will never return a null
return _postalCode ?? "";
}
set
{
_postalCode = value;
}
}
}
You can always loop through the different parts of your class and do a nullCheck using System.Reflection. Here are a couple of examples that transfer a list of generic classes to datatable and datatableRow. You can use the same idea with GetProperties to do null checks as well as transform your class into SQL inserts, CSV data, XML, or anything you need automatically.
public static DataTable create_DataTable_From_Generic_Class(Type t)
{
DataTable d = new DataTable();
FieldInfo[] fI = t.GetFields();
for(int i = 0; i < fI.Length; i++)
{
DataColumn dC = new DataColumn(fI[i].Name, fI[i].FieldType);
d.Columns.Add(dC);
}
return d;
}
public static object[] Create_Datatable_Row_From_Generic_Class(Type t, object instance,DataTable dt)
{
FieldInfo[] f = t.GetFields();
object[] ret = new object[f.Length];
for (int i = 0; i < dt.Columns.Count; i++)
{
ret[i] = t.GetField(dt.Columns[i].ColumnName).GetValue(instance);
if (ret[i] == null)
{
ret[i] = "null";
}
}
return ret;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With