Entity Framework 4.0 Automatically Truncate/Trim String Before Insert

后端 未结 5 864
日久生厌
日久生厌 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:06

    This will give you the max length of a column..

    public int? GetColumnMaxLength(ObjectContext context, string entityTypeName, string columnName)
        {
            int? result = null;
    
            Type entType = Type.GetType(entityTypeName);
            var q = from meta in context.MetadataWorkspace.GetItems(DataSpace.CSpace)
                              .Where(m => m.BuiltInTypeKind == BuiltInTypeKind.EntityType)
                    from p in (meta as EntityType).Properties
                    .Where(p => p.Name == columnName
                                && p.TypeUsage.EdmType.Name == "String")
                    select p;
    
            var queryResult = q.Where(p =>
            {
                bool match = p.DeclaringType.Name == entityTypeName;
                if (!match && entType != null)
                {
                    //Is a fully qualified name....
                    match = entType.Name == p.DeclaringType.Name;
                }
    
                return match;
    
            }).Select(sel => sel.TypeUsage.Facets["MaxLength"].Value);
            if (queryResult.Any())
            {
                result = Convert.ToInt32(queryResult.First());
            }
    
            return result;
        }
    

提交回复
热议问题