none
What's the best practise to initialize non nullable string properties to string.Empty RRS feed

  • Question

  • What's the prefered way to set non nullable varchar columns to the default value of an empty string. I'm working with the slightly customized t4 template based on the default template (ObjectContext etc.)

    It seems the options are to

    a, Edit each and every table in the designer and set all the varchar not null properties to default ""
    b, Customize the T4 Template some more to init it's members to "" in case of varchar not null
    c, ?

    I'd like to understand whether there is any reason why a string property is initialized to null instead of string.Empty if it's not nullable.

    Monday, August 22, 2011 4:34 PM

Answers

  • Hello Daniel,

    There isn't anything to support this specifically built into EF at the moment. Your best bet is probably to override SaveChanges and process your entities before saving your changes.

    I also think it would be a great addition to be able to create a convention to automatically convert null string properties on a model to empty varchars on non-nullable db columns. You could go to the Customer feedback for data access site to submit a suggestion for EF.

    Here is the link: http://data.uservoice.com/pages/72025-ado-net-entity-framework-ef-feature-suggestions?filter=top&page=2

    I hope this can help you.

     

    Have a nice day,

     


    Jackie Sun [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Friday, August 26, 2011 9:19 AM
    Moderator
  • Thank you, i'll take a look into the feature suggestions.

    For now i customized my T4 Template and it seems to work:

    private <#=code.Escape(primitiveProperty.TypeUsage)#> <#=code.FieldName(primitiveProperty)#><#=code.StringBefore(" = ", code.CreateLiteral(getDefaultValueEffective(primitiveProperty)))#>;
    

    ... using string.Empty in case of 'Not Nullable && typeof(string) && defaultValue == null'

    static object getDefaultValueEffective(EdmProperty primitiveProperty)
    {
     // dk, 2011-08-23: Non-nullable string properties should be initialized to "" instead of null.
     if(((PrimitiveType)primitiveProperty.TypeUsage.EdmType).PrimitiveTypeKind == PrimitiveTypeKind.String &&
     primitiveProperty.Nullable == false &&
     primitiveProperty.DefaultValue == null)
     {
     return string.Empty;
     }
     return primitiveProperty.DefaultValue;
    }
    
    
    

     

     

    Friday, August 26, 2011 4:55 PM

All replies

  • I'm thinking change the schema:

    ... VARCHAR(xxx) NOT NULL DEFAULT ''

    Monday, August 22, 2011 5:56 PM
  • I have a default on the column but entity framework doesn't recognize it. So if i create a new entity the field gets initialized to null and SaveChanges() fails since it trys to set the column explicitly to null.

    There doesn't come to much to mind why anyone could want a non nullable string to be initially set to null (good that value types don't have this problem) for an entity. Library styleguides generally require string properties to return empty instead of null etc..

    I wonder if that is a design decision (and what could be the reason for it) or whether noone ever thought about just using the field initializer to init any non nullable string to empty. Especially since the setter does care for null and won't allow it to be set even temporarily.

    Tuesday, August 23, 2011 10:16 AM
  • Hello Daniel,

    There isn't anything to support this specifically built into EF at the moment. Your best bet is probably to override SaveChanges and process your entities before saving your changes.

    I also think it would be a great addition to be able to create a convention to automatically convert null string properties on a model to empty varchars on non-nullable db columns. You could go to the Customer feedback for data access site to submit a suggestion for EF.

    Here is the link: http://data.uservoice.com/pages/72025-ado-net-entity-framework-ef-feature-suggestions?filter=top&page=2

    I hope this can help you.

     

    Have a nice day,

     


    Jackie Sun [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Friday, August 26, 2011 9:19 AM
    Moderator
  • Thank you, i'll take a look into the feature suggestions.

    For now i customized my T4 Template and it seems to work:

    private <#=code.Escape(primitiveProperty.TypeUsage)#> <#=code.FieldName(primitiveProperty)#><#=code.StringBefore(" = ", code.CreateLiteral(getDefaultValueEffective(primitiveProperty)))#>;
    

    ... using string.Empty in case of 'Not Nullable && typeof(string) && defaultValue == null'

    static object getDefaultValueEffective(EdmProperty primitiveProperty)
    {
     // dk, 2011-08-23: Non-nullable string properties should be initialized to "" instead of null.
     if(((PrimitiveType)primitiveProperty.TypeUsage.EdmType).PrimitiveTypeKind == PrimitiveTypeKind.String &&
     primitiveProperty.Nullable == false &&
     primitiveProperty.DefaultValue == null)
     {
     return string.Empty;
     }
     return primitiveProperty.DefaultValue;
    }
    
    
    

     

     

    Friday, August 26, 2011 4:55 PM
  • hello,

    facing the same 'problem', i wrote the following code:

      public static class EntityTools {
        public static void SetDefaults (object o) {
          Type T = o.GetType();
          foreach ( MemberInfo m in T.GetMembers().Where(
            t => t.MemberType == MemberTypes.Property ) ) {
            PropertyInfo P = T.GetProperty(m.Name);
            switch ( P.PropertyType.Name ) {
              case "String" :
                if ( P.GetValue(o, null) == null ) 
                  P.SetValue(o, String.Empty, null); 
                break;
              case "DateTime" :
                if ( (DateTime)P.GetValue(o, null) == DateTime.MinValue )
                  P.SetValue(o, new DateTime(1900, 1, 1, 0, 0, 0), null); 
                break;
            }
          }
        }
      }
    


    thierry
    Friday, August 26, 2011 8:56 PM
  • Great!
    Jackie Sun [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Saturday, August 27, 2011 4:23 AM
    Moderator