我想防止将任何默认值用于Entity Framework核心中的键。例如,00000000-0000-0000-0000-000000000000
代表Guid,0
代表整数,等等
答案 0 :(得分:0)
使用此帮助程序类
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);
}