在EF Core中有唯一约束(代码首先)的数据注释吗?



我想知道在实体框架核心2代码第一个方法中是否有数据注释?

ef core 中,您只能在Fluent API中使用扩展方法 HasAlternateKey 没有数据注释实现唯一约束

此MS Doc文章 - 备用密钥(唯一约束( - 将解释如何使用以及存在哪些可能性。

上面链接的一个简短示例:

class MyContext : DbContext
{
    public DbSet<Car> Cars { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Car>()
            .HasAlternateKey(c => c.LicensePlate)
            .HasName("AlternateKey_LicensePlate");
    }
}
class Car
{
    public int CarId { get; set; }
    public string LicensePlate { get; set; }
    public string Make { get; set; }
    public string Model { get; set; }
}

也可以定义唯一的索引。因此,在 ef core 中,您可以使用流利的API扩展方法HasIndex或属性[Index]的数据注释方式。

在此MS文档文章中 - 索引 - 您将找到更多信息。

在这里
class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>()
            .HasIndex(b => b.Url)
            .IsUnique();
    }
}
public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
}

在这里相同的示例,但使用数据注释

[Index(nameof(Url), IsUnique = true)]
public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
}

更新2021-09-10

  • 添加了其他信息如何与数据注释一起使用,因为现在可以在EF Core中使用;

更新2021-09-24

  • 固定的属性中缺少Isunique属性示例

要更新,现在有一个代码优先注释。

[Index(nameof(MyProperty), IsUnique = true)] // using Microsoft.EntityFrameworkCore
public class MyClass
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public Guid Id { get; set; }
    [StringLength(255), Required]
    public string MyProperty { get; set; }
}

我已经写了一个属性类,可以使您可以装饰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>();
}

在您的实体中用法:

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"的使用"''然后"订单"&quot;(

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

DbContext.cs文件中, OnModelCreating(modelBuilder)方法内,最后一个 ForEach,我有 .OrderBy(o => o.Order)

最新更新