实体框架4.0在插入之前自动截断/修剪字符串 [英] Entity Framework 4.0 Automatically Truncate/Trim String Before Insert

查看:81
本文介绍了实体框架4.0在插入之前自动截断/修剪字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个表,其列为Description,varchar(100)。如果尝试插入长度超过100个字符的字符串,则插入将失败。

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.

Entity Framework中是否有一种方法可以自动截断或修剪字符串以使其适合列插入列之前?在我的场景中,我真的不在乎字符串是否被截断,我只是希望将其插入而不是仅仅失败并记录错误。

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.

由于模型已经知道长度限制,我当时想Entity Framework可能会为我做到这一点。

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

如果不支持此操作,最好的方法是什么?扩展自动生成的部分类并覆盖On * Changed方法?我不希望对长度限制进行硬编码,而要使用实体模型中已经定义的长度限制。我如何获得此权限?

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?

编辑

我的最终解决方案是实现自动生成的实体的On * Changed部分方法。

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

我使用了,然后使用以下方法提取最大长度并截断字符串。 / p>

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.

推荐答案

这将为您提供一列的最大长度。

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

这篇关于实体框架4.0在插入之前自动截断/修剪字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆