在 Entity Framework 7 中,哪个 属性 属性首先在代码中创建索引?
In Entity Framework 7 which property Attribute creates an index in code first?
在Entity Framework 7 (7.0.0-rc1-final)中哪个属性属性创建了一个索引?
我通常会将索引添加到 sql table 以缩短查找时间,因此我假设我需要在我的 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; }
}
我假设 [Index] 会这样做,但无法识别。
如何索引 ApplicationUserId 列?
在你的 DbContext class 中使用流利的 API:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Account>()
.HasIndex(b => b.ApplicationUserId);
}
解决方法如下:
[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 });
}
}
}
}
在Entity Framework 7 (7.0.0-rc1-final)中哪个属性属性创建了一个索引?
我通常会将索引添加到 sql table 以缩短查找时间,因此我假设我需要在我的 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; }
}
我假设 [Index] 会这样做,但无法识别。
如何索引 ApplicationUserId 列?
在你的 DbContext class 中使用流利的 API:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Account>()
.HasIndex(b => b.ApplicationUserId);
}
解决方法如下:
[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 });
}
}
}
}