Максимальная длина поля в структуре Entity

Это также может быть проблема безопасности?

int main()
{
    int array[10];
    int i;
    for (i = 0; i <= 10; ++i)
    {
        array[i] = 0;
    }
}

Если массив меньше в стеке, чем i, этот код будет циклически бесконечно (потому что он ошибочно обращается к нулевому массиву [10], что я). Помещая массив выше в стеке, попытки доступа к памяти за пределами стека будут чаще касаться нераспределенной памяти и сбой, а не вызывать неопределенное поведение.

Я экспериментировал с этим же кодом один раз с gcc и не смог выполнить его, за исключением конкретной комбинации флагов, которые я не помню сейчас. В любом случае он разместил массив несколько байтов от i.

23
задан Zach Johnson 15 March 2011 в 20:06
поделиться

3 ответа

Вот как мне удается это сделать (с помощью метода расширения для сущностей):

public static int? GetMaxLength(this EntityObject entite, string nomPropriete)
    {
        int? result = null;
        using (XEntities contexte = XEntities.GetCurrentContext())
        {
            var queryResult = from meta in contexte.MetadataWorkspace.GetItems(DataSpace.CSpace)
                               .Where(m => m.BuiltInTypeKind == BuiltInTypeKind.EntityType)
                              from p in (meta as EntityType).Properties
                                 .Where(p => p.DeclaringType.Name == entite.GetType().Name
                                     && p.Name == nomPropriete
                                     && p.TypeUsage.EdmType.Name == "String")
                              select p.TypeUsage.Facets["MaxLength"].Value;
            if (queryResult.Count() > 0)
            {
                result = Convert.ToInt32(queryResult.First());
            }
        }
        return result;
    }
37
ответ дан 29 November 2019 в 02:01
поделиться

Update

I realize that this answer doesn't directly apply to EF. At the time that I answered, there had been no answers for about 20 minutes and I thought knowing how I solved a similar problem with LINQToSQL might help. Given that the OP basically used the same technique albeit with EF properties instead, seems to indicate that I made the right choice. I'm leaving this answer here for context and for those who get here having the same problem but with LINQToSQL.

Original

I don't know about EF, but LINQToSQL entity properties are decorated with ColumnAttributes. You may be able to get the ColumnAttribute from the PropertyInfo for the property by looking at the CustomAttributesCollection. The value of this attribute would need to be parsed for length. I do that in my validator classes to make sure that I'm not going to get a SQL error by using a string that is too long for my column.

This is the method I use to extract the column length for string properties.

    public static int MaximumPropertyLength( Type type, string propertyName )
    {
        int maximumLength = -1;
        PropertyInfo info = type.GetProperty( propertyName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance );
        if (info != null)
        {
            var attribute = info.GetCustomAttributes( typeof( ColumnAttribute ), false )
                                .Cast<ColumnAttribute>()
                                .FirstOrDefault();
            if (attribute != null)
            {
                maximumLength = ExtractLength( attribute.DbType );
            }
        }
        return maximumLength;
    }

    private static int ExtractLength( string dbType )
    {
        int max = int.MaxValue;
        if (dbType.Contains( "(" ))
        {
            string[] parts = dbType.Split( new char[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries );
            if (parts.Length > 1)
            {
                int.TryParse( parts[1], out max );
            }
        }
        return max;
    }
3
ответ дан 29 November 2019 в 02:01
поделиться

Для EntityFramework вам нужно будет добавить свои собственные настраиваемые атрибуты в классы, использующие генератор кода или шаблон T4.

Тогда то, что сказал Тванфоссон выше, будет верным. EF не сохраняет эту информацию по умолчанию.

http://blogs.msdn.com/adonet/archive/2008/01/24/customizing-code-generation-in-the-ado-net-entity-designer.aspx

Подробнее о том, что я я говорю с вашим генератором кода.Это довольно гладко. Я сделал именно то, о чем вы говорите раньше, проблема в проприетарном коде, поэтому у меня нет примера для вас.

1
ответ дан 29 November 2019 в 02:01
поделиться
Другие вопросы по тегам:

Похожие вопросы: