Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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<Car> Cars { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Car>()
            .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. Therefore, in EF Core you can use the fluent API's extension method HasIndex or the data annotation way with the attribute [Index].

In this MS doc article - Indexes - you will find further information how to use.

Here an example for an unique index with fluent API:

class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>()
            .HasIndex(b => b.Url)
            .IsUnique();
    }
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
}

Here the same example, but with data annotation:

[Index(nameof(Url), IsUnique = true)]
public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
}

Update 2021-09-10

  • added additional info how to use with data annotation, because it's now available in EF Core;

Update 2021-09-24

  • fixed missing IsUnique property in attribute example

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...