我找不到方法添加一个唯一的约束我的字段使用属性:
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",
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; }
}
EF芯解决方案
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Passport { get; set; }
}
public class ApplicationContext : DbContext
{
public DbSet<User> Users { get; set; }
public ApplicationContext()
{
Database.EnsureCreated();
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=efbasicsappdb;Trusted_Connection=True;");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().HasAlternateKey(u => u.Passport);
//or: modelBuilder.Entity<User>().HasAlternateKey(u => new { u.Passport, u.Name})
}
}
DB表是这样的:
CREATE TABLE [dbo].[Users] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (MAX) NULL,
[Passport] NVARCHAR (450) NOT NULL,
CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [AK_Users_Passport] UNIQUE NONCLUSTERED ([Passport] ASC)
);
参考EF Core文档