我编写了一个 Attribute 类,它可以让您装饰 EF Core Entity 类属性以生成唯一键(无需 Fluent API)。
using System;
using System.ComponentModel.DataAnnotations;
/// <summary>
/// Used on an EntityFramework Entity class to mark a property to be used as a Unique Key
/// </summary>
[AttributeUsageAttribute(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public class UniqueKeyAttribute : ValidationAttribute
{
/// <summary>
/// Marker attribute for unique key
/// </summary>
/// <param name="groupId">Optional, used to group multiple entity properties together into a combined Unique Key</param>
/// <param name="order">Optional, used to order the entity properties that are part of a combined Unique Key</param>
public UniqueKeyAttribute(string groupId = null, int order = 0)
{
GroupId = groupId;
Order = order;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// we simply return success as no actual data validation is needed because this class implements a "marker attribute" for "create a unique index"
return ValidationResult.Success;
}
public string GroupId { get; set; }
public int Order { get; set; }
}
在您的 DbContext.cs 文件中,在 OnModelCreating(modelBuilder) 方法中,添加以下内容:
// Iterate through all EF Entity types
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
{
#region Convert UniqueKeyAttribute on Entities to UniqueKey in DB
var properties = entityType.GetProperties();
if ((properties != null) && (properties.Any()))
{
foreach (var property in properties)
{
var uniqueKeys = GetUniqueKeyAttributes(entityType, property);
if (uniqueKeys != null)
{
foreach (var uniqueKey in uniqueKeys.Where(x => x.Order == 0))
{
// Single column Unique Key
if (String.IsNullOrWhiteSpace(uniqueKey.GroupId))
{
entityType.AddIndex(property).IsUnique = true;
}
// Multiple column Unique Key
else
{
var mutableProperties = new List<IMutableProperty>();
properties.ToList().ForEach(x =>
{
var uks = GetUniqueKeyAttributes(entityType, x);
if (uks != null)
{
foreach (var uk in uks)
{
if ((uk != null) && (uk.GroupId == uniqueKey.GroupId))
{
mutableProperties.Add(x);
}
}
}
});
entityType.AddIndex(mutableProperties).IsUnique = true;
}
}
}
}
}
#endregion Convert UniqueKeyAttribute on Entities to UniqueKey in DB
}
同样在你的 DbContext.cs 类中,添加这个私有方法:
private static IEnumerable<UniqueKeyAttribute> GetUniqueKeyAttributes(IMutableEntityType entityType, IMutableProperty property)
{
if (entityType == null)
{
throw new ArgumentNullException(nameof(entityType));
}
else if (entityType.ClrType == null)
{
throw new ArgumentNullException(nameof(entityType.ClrType));
}
else if (property == null)
{
throw new ArgumentNullException(nameof(property));
}
else if (property.Name == null)
{
throw new ArgumentNullException(nameof(property.Name));
}
var propInfo = entityType.ClrType.GetProperty(
property.Name,
BindingFlags.NonPublic |
BindingFlags.Public |
BindingFlags.Static |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
if (propInfo == null)
{
return null;
}
return propInfo.GetCustomAttributes<UniqueKeyAttribute>();
}
在 Entity.cs 类中的用法:
public class Company
{
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid CompanyId { get; set; }
[Required]
[UniqueKey(groupId: "1", order: 0)]
[StringLength(100, MinimumLength = 1)]
public string CompanyName { get; set; }
}
您甚至可以在多个属性中使用它来跨表中的多个列形成唯一键。 (注意使用“groupId”,然后是“order”)
public class Company
{
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid CompanyId { get; set; }
[Required]
[UniqueKey(groupId: "1", order: 0)]
[StringLength(100, MinimumLength = 1)]
public string CompanyName { get; set; }
[Required]
[UniqueKey(groupId: "1", order: 1)]
[StringLength(100, MinimumLength = 1)]
public string CompanyLocation { get; set; }
}