Is there an option to make Entity Framework revert empty strings to null?

后端 未结 8 923
时光说笑
时光说笑 2021-02-06 09:30

I am using an ADO.NET Entity-Framework ObjectContext to access my data store.

I want the if values are set with empty strings, they should automatically become null.

8条回答
  •  终归单人心
    2021-02-06 09:58

    Rather than complicating things by overriding the ObjectContext I use string extension methods to convert values for database storage

    public static class StringExtensions
    {
        public static string EmptyStringToNull(this string s)
        {
            return string.IsNullOrWhiteSpace(s) ? null : s;
        }
    
        public static object EmptyStringToDBNull(this string s)
        {
            if (string.IsNullOrWhiteSpace(s)) 
                return DBNull.Value;
            else 
                return s;
        }
    }
    

提交回复
热议问题