Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 Entity Framework to automatically truncate or trim the string to fit into the column before inserting into the column? In my scenario, I really don't care whether the string is truncated, I just want it inserted rather than just failing and logging the rror.

Since the model already knows the length limits, I was thinking there might be a way for Entity Framework to do this for me.

If this is not supported, what is the best way to do this? Extend the auto-generated partial classes and override the On*Changed methods? I would prefer not to hard-code the length limits, but rather use the length limits already defined in the entity model. How could I get access to this?

Edit

My final solution was to implement the On*Changed partial method of the autogenerated entity.

I used this method of getting the ObjectContext from the entity instance, and then used the below method to extract the max length, and truncate the string.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
636 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...