我找不到方法添加一个唯一的约束我的字段使用属性:
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",
自从实体框架核心(EF核心)5.0以来,我们可以通过数据注释配置唯一索引。
它与例如EF6略有不同,因为我们不能在属性本身上设置它,而是在类上设置它。
using Microsoft.EntityFrameworkCore; // for [Index] attribute
using System.ComponentModel.DataAnnotations; // for [Key] and [Required] attributes
namespace FunWithDataAnnotations
{
[Index(nameof(EmailAddress), IsUnique = true)]
public class User
{
[Key]
public Guid Id { get; set; }
[Required]
public string FullName { get; set; }
[Required]
public string EmailAddress { get; set; }
}
}
有关索引和数据注释的更多信息,请参见:https://learn.microsoft.com/en-us/ef/core/modeling/indexes?tabs=data-annotations
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文档