c# - 唯一约束不适用于 Entity Framework Core
问题描述
我正在使用 Entity Framework Core 2.2.6,我有两个实体Profile
和Category
. 每个Category
人都ProfileId
必须确定Profile
它属于哪个。我正在尝试为Name
和ProfileId
in强制执行唯一性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();
。但两者似乎都不起作用。请问你能帮忙解决我哪里出错了吗?
解决方案
推荐阅读
- css - 使用 flexbox 时,CanvasJS 图表占据整行
- javascript - 无论输入如何,都会显示相同的布尔结果
- amazon-web-services - 滚动更新采用旧的实例配置并将它们放在新的配置中?
- azure-iot-hub - Azure 函数应用:“找不到 Microsoft.ServiceBus”
- python - PermissionError:[Errno 13] 权限被拒绝:我的计算机中持续存在问题(Windows 10 专业版)
- json - 自动添加括号以完成 JSON 文件
- c# - C# .NET 从外部文件运行代码
- java - 我有几个活动要使用标签串在一起
- mysql - 当我尝试使用 FOR UPDATE NOWAIT 时,MariaDB 抛出错误
- ansible - 如何在ansible中将dict格式化为字符串