c# - How to save null strings as string.empty when saving changes? -


say have class (details omitted brevity):

public class address {     public address()     {         postalcode = "";     }     public string postalcode { get; set; }  } 

in mapping, postal code marked required:

public addressmap() {     this.property(t => t.postalcode)         .hascolumnname("postalcode")         .isrequired()         .hasmaxlength(50); } 

in database defined follows:

create table [dbo].[address] (   [postalcode]   varchar (50)   not null   default (('')) ); 

it initialized in code null value postalcode:

string pc = null; var address = new address() {      postalcode = pc  }; 

when go add address dbcontext, , save changes, dbentityvalidationexception because i'm trying save null value not null column.

is there way have entity framework or database not attempt save .isrequired string column null instead save empty string?

one option change get accessor of property remove null values:

public class address {     private string _postalcode;      public address()     {         postalcode = "";     }      public string postalcode      {                  {             //this never return null             return _postalcode ?? "";         }         set         {             _postalcode = value;         }      } } 

Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -