我正在使用Entity Framework Core 2.2.6,并且我有两个实体Profile
和Category
。每个Category
将具有ProfileId
来标识它属于哪个Profile
。我试图对Name
中的ProfileId
和Category
强制执行唯一性。但是我唯一的约束失败了。
这是我的实体,
BaseEntity:
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();
。但是两者似乎都不起作用。请帮我解决问题吗?