Entity Framework Core add unique constraint code-first

前端 未结 9 976
南方客
南方客 2020-12-12 17:36

I can\'t find way to add a unique constraint to my field with using attribute:

public class User
{
    [Required]
    public int Id { get; set; }

    [Requi         


        
相关标签:
9条回答
  • 2020-12-12 18:07

    Also if you want to create Unique constrains on multiple columns you can simply do this (following @Sampath's link)

    class MyContext : DbContext
    {
        public DbSet<Person> People { get; set; }
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Person>()
                .HasIndex(p => new { p.FirstName, p.LastName })
                .IsUnique(true);
        }
    }
    
    public class Person
    {
        public int PersonId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    
    0 讨论(0)
  • 2020-12-12 18:09

    We can add Unique key index by using fluent api. Below code worked for me

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
    
            modelBuilder.Entity<User>().Property(p => p.Email).HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_EmailIndex") { IsUnique = true }));
    
        }
    
    0 讨论(0)
  • 2020-12-12 18:14

    None of these methods worked for me in .NET Core 2.2 but I was able to adapt some code I had for defining a different primary key to work for this purpose.

    In the instance below I want to ensure the OutletRef field is unique:

    public class ApplicationDbContext : IdentityDbContext
        {
            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                base.OnModelCreating(modelBuilder);
                modelBuilder.Entity<Outlet>()
                    .HasIndex(o => new { o.OutletRef });
            }
        }
    
    

    This adds the required unique index in the database. What it doesn't do though is provide the ability to specify a custom error message.

    0 讨论(0)
  • 2020-12-12 18:15

    Solution for EF Core

    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 table will look like this:

    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)
    );
    

    Ref to EF Core docs

    0 讨论(0)
  • 2020-12-12 18:20

    On EF core you cannot create Indexes using data annotations.But you can do it using the Fluent API.

    Like this inside your {Db}Context.cs:

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<User>()
            .HasIndex(u => u.Email)
            .IsUnique();
    }
    

    ...or if you're using the overload with the buildAction:

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<User>(entity => {
            entity.HasIndex(e => e.Email).IsUnique();
        });
    }
    

    You can read more about it here : Indexes

    0 讨论(0)
  • 2020-12-12 18:20

    Ef core support unique configuration.

    protected override void OnModelCreating(ModelBuilder builder)
    {
      builder.Entity<Account>()
        .HasIndex(account => account.Email)
          .IsUnique();
    }
    

    Ef core support multiple unique keys

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
      modelBuilder.Entity<Account>()
          .HasKey(account => new { account.Id, account.Email, account.RoleId });
    }
    

    Don't forget run ef core command to make migration and update the database

    >> dotnet ef migrations add MigrationName -c YourDbContextName
    >> dotnet ef database update -c YourDbContextName
    
    0 讨论(0)
提交回复
热议问题