First, set the index
protected the override void OnModelCreating (the ModelBuilder modelBuilder)
{
modelBuilder.Entity <Blog> () .HasIndex (B => b.Url); // the Url field index
modelBuilder.Entity <Blog> () .HasIndex ( b => b.Url ) .IsUnique (); unique index // Url field
. modelBuilder.Entity <Blog> () HasIndex (b => b.Url) .HasName ( "Index_Url"); // set the index name Index_Url
modelBuilder.Entity < . blog> () HasIndex (b => b.Url) .HasFilter ( " filter"); // index data inside the composite HasFilter fill condition where conditions. All data HasFilter (null) indexing
modelBuilder.Entity <the Person> () .HasIndex (P => new new {p.FirstName, p.LastName}); // create a plurality of columns of an index
}
Second, the alternate key: In addition to the primary key, alternate key can uniquely identify a data (with the same unique primary key constraint). Alternate key may be used as a target foreign key relationships. When using a relational database, the system will usually default when you need to introduce alternate key, you need to manually configure them, of course, you can manually configure
1, agreed to set: By convention, when the property that you identified as the primary key is not the target of the relationship, will be introducing you to spare key
class MyContext: the DbContext { public DbSet <Blog> Blogs { GET ; SET ;} public DbSet <Post> Posts { GET ; SET ;} protected the override void OnModelCreating (the ModelBuilder modelBuilder) { modelBuilder.Entity <Post> () .HasOne (P => p.Blog) .WithMany (B => b.Posts) .HasForeignKey (P => p.BlogUrl) .HasPrincipalKey (B => b.Url); // no need to provide a spare key Url, EF Core will set up } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } public List<Post> Posts { get; set; } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public string BlogUrl { get; set; } public Blog Blog { get; set; } }
2, manual setting: Fluent API can be used to manually configure a single attribute alternate key
protected the override void OnModelCreating (the ModelBuilder modelBuilder)
{
modelBuilder.Entity <Car> ()
.HasAlternateKey (C => c.LicensePlate) // single attribute alternate key
.HasName ( "AlternateKey_LicensePlate"); // set alternate key name
modelBuilder.Entity <Car> () .HasAlternateKey (C => new new {c.State, c.LicensePlate}); // set the composite alternate key
}
Note: By convention, the alternate key index and constraints is named AK_ <type name> _ <property name> format, the standby key combination <property name> is the name attribute partition list underscore