3

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?

5 Answers 5

3

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;
        } 
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

changing the setter would work, but i was wondering if there was a solution to automatically do that on the context or some sort of setting. ex: set { _postalCode = value ?? ""; }
The only other way I can think of would be to loop through the entities in the context before you save your changes and change the values there. But that's really quite a lot of work.
Agreed, I would imagine that it would be expensive and slow.
It all depends on your use case of course, but this answer is the simplest and quickest method. It also keeps your logic inside the entity.
1

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;

    }

2 Comments

Hi @Shannon - I could override the SaveChanges() method to loop over added/changed entities' properties, and use reflection, but I worry that it would be a slow and expensive task - and would have a pretty large impact on my application's performance.
Idk - I use this on 14Million to 1.2Billion records pretty frequently and it seems to work fine. You can go async with it if you don't mind which order the data comes in in terms of rows.
1

For some reason answer didn't worked for me. Most probably because of some EF underlying setting. But, adding AllowEmptyStrings = true on [Required], i.e.

[Required(AllowEmptyStrings = true)]

solved the problem.

P.S. I had [Required] on string property which is minor difference comparing to question asked.

Comments

0

Why do you initializate the String to null? May be if you use:

string pc = String.Empty;

var address = New Address() {    PostalCode = pc  };

if you want to assure that never is null you could use the solution from @DavidG but if you want to check when is null may be you need to just initializating to String.Empty

1 Comment

Hi @amalbala - that was just a simplified example. Lets say that i assign postal code a string returned from a 3rd party service. That string can sometimes be null, and lets say that I have issues like this in 2000 places in my code base.
0

Perhaps setting Configuration.ValidateOnSaveEnabled = false in your context class before calling SaveChanges() will work.

context.Configuration.ValidateOnSaveEnabled = false;
context.SaveChanges();

Entity Framework/MVC3: temporarily disable validation

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.