我找不到方法添加一个唯一的约束我的字段使用属性:
public class User
{
[Required]
public int Id { get; set; }
[Required]
// [Index("IX_FirstAndSecond", 2, IsUnique = true)] not supported by core
public string Email { get; set; }
[Required]
public string Password { get; set; }
}
我正在使用这些包:
"Microsoft.EntityFrameworkCore": "1.0.1",
"Microsoft.EntityFrameworkCore.SqlServer": "1.0.1",
"Microsoft.EntityFrameworkCore.SqlServer.Design": "1.0.1",
"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",
在。net Core 2.2中,这些方法都不适合我,但我可以调整一些代码,定义一个不同的主键来实现这个目的。
在下面的例子中,我想确保OutletRef字段是唯一的:
public class ApplicationDbContext : IdentityDbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Outlet>()
.HasIndex(o => new { o.OutletRef });
}
}
这将在数据库中添加所需的惟一索引。
但是它没有提供指定自定义错误消息的能力。
OP询问是否可以为唯一键添加一个属性到实体类中。简单的回答是,这是可能的,但不是EF核心团队的一个开箱即用的功能。
如果你想使用一个属性为你的实体框架核心实体类添加唯一键,你可以做我在这里发布的
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; }
}