Предотвращение использования значений по умолчанию для ключей в Entity Framework Core? - PullRequest
0 голосов
/ 15 мая 2019

Я хотел бы запретить любые значения по умолчанию для типа, используемого для ключей в ядре Entity Framework.Так, например, 00000000-0000-0000-0000-000000000000 для направляющих, 0 для целых и т. Д.

1 Ответ

0 голосов
/ 15 мая 2019

Использование этого вспомогательного класса

static class KeyValidator
{
    public static void ValidateKeys(this DbContext context)
    {
        foreach (var entity in context.AddedOrModified())
        {
            foreach (var key in entity.Metadata.GetKeys())
            {
                foreach (var property in key.Properties)
                {
                    var propertyEntry = entity.Property(property.Name);

                    if (!IsDefaultValue(property.ClrType, propertyEntry.CurrentValue))
                    {
                        continue;
                    }

                    throw new Exception($@"Invalid empty key.
EntityType: {entity.Metadata.ClrType.FullName}
PropertyName: {property.Name}
PropertyType: {property.ClrType.FullName}.");
                }
            }
        }
    }

    static bool IsDefaultValue(Type clrType, object currentValue)
    {
        if (clrType.IsValueType)
        {
            var instance = Activator.CreateInstance(clrType);
            return instance.Equals(currentValue);
        }

        return currentValue == null;
    }

    static IEnumerable<EntityEntry> AddedOrModified(this DbContext context)
    {
        return context.ChangeTracker.Entries()
            .Where(e => e.State == EntityState.Added ||
                        e.State == EntityState.Modified);
    }
}

В DbContext входят

public override int SaveChanges()
{
    this.ValidateKeys();
    return base.SaveChanges();
}

public override Task<int> SaveChangesAsync(bool acceptAllChanges, CancellationToken cancellation = default)
{
    this.ValidateKeys();
    return base.SaveChangesAsync(acceptAllChanges, cancellation);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...