Entity Framework 4.0 Automatically Truncate/Trim String Before Insert

后端 未结 5 846
日久生厌
日久生厌 2020-12-30 04:36

Suppose I have a table with the column Description, varchar(100). If try to insert a string with more than 100 characters, the insert will fail.

Is there a way in En

5条回答
  •  孤城傲影
    2020-12-30 05:00

    I used a slightly different tack, but also utilizing the On*Changed methods. I'm generating partial classes using a stripped down version of the .tt file used by EF. The relevant section is where the properties are generated. The Maximum length is available and can be used to truncate the string.

     foreach (EdmProperty property in 
             entity.Properties.Where(p => p.DeclaringType == entity 
             && p.TypeUsage.EdmType is PrimitiveType))
     {
    
            /// If this is a string implements its OnChanged method
            if (property.TypeUsage.ToString() != "Edm.String") continue;
    
            int maxLength = 0;
    
            if (property.TypeUsage.Facets["MaxLength"].Value == null) continue;
    
            if (!Int32.TryParse(property.TypeUsage.Facets["MaxLength"].Value.ToString(), 
                out maxLength)) continue;
    
            if (maxLength == 0) continue;
            // Implement the On*Changed method
    
            #>
            partial void On<#= property.Name#>Changed() {
                <#=code.FieldName(property)#> =#=code.FieldName(property)#>.Substring(0,<#= maxLength #>);
    
            } 
            <#
        } 
    

提交回复
热议问题