[entity-framework] 먼저 코드를 사용하여 Entity Framework 6.2에서 인덱스를 만드는 방법

new를 사용하는 대신 코드 우선을 사용하여 속성 / 열에 인덱스를 만드는 방법이 IndexAttribute있습니까?



답변

잘 26.10.2017 Entity Framework 6.2가 공식적으로 출시되었습니다 . 그것은 포함 가능성 유창함 API를 통해 쉽게 인덱스를 정의 할 수 있습니다. 사용하는 것은 이미 6.2의 베타에서 발표 되었습니다.

이제 HasIndex()방법을 사용할 IsUnique()수 있으며 고유 인덱스 여야 하는 경우 뒤에 올 수 있습니다 .

간단한 비교 (전 / 후) 예 :

// before 
modelBuilder.Entity<Person>()
        .Property(e => e.Name)
        .HasColumnAnnotation(
            IndexAnnotation.AnnotationName,
            new IndexAnnotation(new IndexAttribute { IsUnique = true }));

// after
modelBuilder.Entity<Person>()
    .HasIndex(p => p.Name)
    .IsUnique();

// multi column index
modelBuilder.Entity<Person>()
    .HasIndex(p => new { p.Name, p.Firstname })
    .IsUnique();

인덱스를로 클러스터 된 것으로 표시 할 수도 있습니다 .IsClustered().


# 1 수정

다중 열 인덱스에 대한 예제와 인덱스를 클러스터형으로 표시하는 방법에 대한 추가 정보를 추가했습니다.


# 2 수정

추가 정보로 EF Core 2.1에서는 현재 EF 6.2와 완전히 동일합니다.
다음 은 MS Doc 기사입니다.


답변

현재 유창한 API를 통해 색인을 생성하기위한 “일급 지원” 은 없지만 유창한 API를 통해 속성을 Annotation API의 속성이있는 것으로 표시 할 수 있습니다. 이렇게하면 Index유창한 인터페이스를 통해 속성 을 추가 할 수 있습니다 .

다음은 EF에 대한 문제 사이트의 작업 항목에 대한 몇 가지 예입니다.

단일 열에 인덱스를 만듭니다.

modelBuilder.Entity<MyEntity>()
    .Property(e => e.MyProperty)
    .HasColumnAnnotation(
        IndexAnnotation.AnnotationName,
        new IndexAnnotation(new IndexAttribute()));

단일 열에 여러 인덱스 :

modelBuilder.Entity<MyEntity>()
    .Property(e => e.MyProperty)
    .HasColumnAnnotation(
        IndexAnnotation.AnnotationName,
        new IndexAnnotation(new[]
            {
                new IndexAttribute("Index1"),
                new IndexAttribute("Index2") { IsUnique = true }
            }));

다중 열 인덱스 :

modelBuilder.Entity<MyEntity>()
    .Property(e => e.MyProperty1)
    .HasColumnAnnotation(
        IndexAnnotation.AnnotationName,
        new IndexAnnotation(new IndexAttribute("MyIndex", 1)));

modelBuilder.Entity<MyEntity>()
    .Property(e => e.MyProperty2)
    .HasColumnAnnotation(
        IndexAnnotation.AnnotationName,
        new IndexAnnotation(new IndexAttribute("MyIndex", 2)));

위의 기술을 사용하면 다음 마이그레이션을 스캐 폴드 할 때 함수 .CreateIndex()에서 호출이 자동으로 생성됩니다 Up()(또는 마이그레이션을 사용하지 않는 경우 데이터베이스에서 자동으로 생성됨).


답변

이 작업을 훨씬 쉽게하기 위해 몇 가지 확장 메서드를 만들고 nuget 패키지로 래핑했습니다.

EntityFramework.IndexingExtensions너겟 패키지를 설치하십시오 .

그런 다음 다음을 수행 할 수 있습니다.

public class MyDataContext : DbContext
{
  protected override void OnModelCreating(DbModelBuilder modelBuilder)
  {
    modelBuilder.Entity<Customer>()
        .HasIndex("IX_Customers_Name",          // Provide the index name.
            e => e.Property(x => x.LastName),   // Specify at least one column.
            e => e.Property(x => x.FirstName))  // Multiple columns as desired.

        .HasIndex("IX_Customers_EmailAddress",  // Supports fluent chaining for more indexes.
            IndexOptions.Unique,                // Supports flags for unique and clustered.
            e => e.Property(x => x.EmailAddress));
  }
}

프로젝트 및 소스 코드는 여기에 있습니다 . 즐겨!


답변

명시적인 이름없이 :

[Index]
public int Rating { get; set; } 

특정 이름으로 :

[Index("PostRatingIndex")]
public int Rating { get; set; }


답변

EF 6.1부터 특성 [Index]이 지원됩니다. 고유 색인에
사용 [Index(IsUnique = true)]합니다.
다음은 Microsoft링크입니다.

public class User
{
    public int UserId { get; set; }

    [Index(IsUnique = true)]
    [StringLength(200)]
    public string Username { get; set; }

    public string DisplayName { get; set; }
}


답변

Entity Framework 6

Property(c => c.MyColumn)
        .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_MyIndex")));

다음을 사용하여 추가하십시오.

using System.Data.Entity.Infrastructure.Annotations;
using System.ComponentModel.DataAnnotations.Schema;


답변

INDEX 데이터 주석 코드 첫 번째 데이터 주석을 사용할 수 있습니다.