Is there a data annotation for unique constraint in EF Core (code first)?

后端 未结 2 2147
北荒
北荒 2020-12-16 02:47

I am wondering if there is a data annotation for unique constraint in Entity Framework Core 2 code first approach?

2条回答
  •  [愿得一人]
    2020-12-16 03:25

    In EF Core You could use the extension method HasAlternateKey in fluent API only. There are no data annotations to realize a unique constraint.

    This MS doc article - Alternate Keys (Unique Constraints) - will explain how to use and which further possibilities are exist.

    A short example from link above:

    class MyContext : DbContext
    {
        public DbSet Cars { get; set; }
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity()
                .HasAlternateKey(c => c.LicensePlate)
                .HasName("AlternateKey_LicensePlate");
        }
    }
    
    class Car
    {
        public int CarId { get; set; }
        public string LicensePlate { get; set; }
        public string Make { get; set; }
        public string Model { get; set; }
    }
    

    Also it's possible to define an unique index. Therefor in EF Core you have to use in fluent API the extension method HasIndex (no data annotations). In this MS doc article - Indexes - you will find further information.

    And here an example for an unique index:

    class MyContext : DbContext
    {
        public DbSet Blogs { get; set; }
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity()
                .HasIndex(b => b.Url)
                .IsUnique();
        }
    }
    
    public class Blog
    {
        public int BlogId { get; set; }
        public string Url { get; set; }
    }
    

提交回复
热议问题