In Entity Framework 7 (7.0.0-rc1-final) which property Attribute creates an index?
I would normally add an index to a sql table to improve look up times so I assume I need to specify this in my class?
public class Account
{
[Key]
[Required]
public int AccountId { get; set; }
[Required] <-- How do I make this an Index in Sql Server?
public int ApplicationUserId { get; set; }
}
I assume [Index] would do it but this is not recognised.
How do I index the ApplicationUserId column?
Use the fluent API in your DbContext class:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Account>()
.HasIndex(b => b.ApplicationUserId);
}
Here is a workaround:
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
public class IndexAttribute : Attribute
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
foreach (var entity in modelBuilder.Model.GetEntityTypes())
{
foreach (var property in entity.GetProperties())
{
if (property.PropertyInfo != null && property.PropertyInfo.GetCustomAttributes<IndexAttribute>().Any())
{
entity.AddIndex(new[] { property });
}
}
}
}