首页 > 解决方案 > 唯一约束不适用于 Entity Framework Core

问题描述

我正在使用 Entity Framework Core 2.2.6,我有两个实体ProfileCategory. 每个Category人都ProfileId必须确定Profile它属于哪个。我正在尝试为NameProfileIdin强制执行唯一性Category。但是,我的独特约束失败了。

这是我的实体,

基本实体:

public class BaseEntity<TKey>
{
    public TKey Id { get; set; }
    public bool Active { get; set; }
    public DateTimeOffset CreatedAt { get; set; }
    public string CreatedBy { get; set; }
    public DateTimeOffset? ModifiedAt { get; set; }
    public string ModifiedBy { get; set; }
}

轮廓:

public class Profile : BaseEntity<Guid>, IAggregateRoot
{
    private Profile()
    {
        // required by EF
    }

    public Profile(string brandName)
    {
        Guard.Against.NullOrEmpty(brandName, nameof(brandName));
        BrandName = brandName;
    }

    public string BrandName { get; set; }
    public string Caption { get; set; }
}

类别:

public class Category : BaseEntity<Guid>, IAggregateRoot
{
    private Category()
    {
        // required by EF
    }

    public Category(string name)
    {
        Guard.Against.NullOrEmpty(name, nameof(name));
        Name = name;
    }

    public Category(string name, string code) : this(name)
    {
        Guard.Against.NullOrEmpty(code, nameof(code));

        Code = code;
    }

    public string Name { get; set; }
    public string Code { get; set; }

    public Guid ProfileId { get; set; }
}

类别实体配置:

public class CategoryConfiguration : IEntityTypeConfiguration<Category>
{
    public void Configure(EntityTypeBuilder<Category> builder)
    {
        builder.HasAlternateKey(c => new { c.ProfileId, c.Name });
        // builder.HasIndex(c => new { c.ProfileId, c.Name }).IsUnique();

        builder.Property(c => c.Name)
            .IsRequired()
            .HasMaxLength(50);

        builder.Property(c => c.Code)
            .HasMaxLength(10);

        builder.HasOne<Profile>()
             .WithMany()
             .HasForeignKey(p => p.ProfileId)
             .IsRequired();
    }
}

我试过builder.HasAlternateKey(c => new { c.ProfileId, c.Name });builder.HasIndex(c => new { c.ProfileId, c.Name }).IsUnique();。但两者似乎都不起作用。请问你能帮忙解决我哪里出错了吗?

标签: c#unique-constraintasp.net-core-2.2ef-core-2.2

解决方案


推荐阅读