developer tip

엔터티 프레임 워크 코드에서 먼저 여러 열에 KeyAttribute를 사용하는 방법

optionbox 2020. 9. 7. 08:01
반응형

엔터티 프레임 워크 코드에서 먼저 여러 열에 KeyAttribute를 사용하는 방법


엔티티 프레임 워크 코드 우선 CTP5와 함께 사용할 POCO 모델을 만들고 있습니다. 장식을 사용하여 PK 열에 속성 맵을 만듭니다. 그러나 두 개 이상의 열에서 PK를 어떻게 정의 할 수 있습니까? 특히 인덱스의 열 순서를 어떻게 제어 할 수 있습니까? 클래스의 속성 순서의 결과입니까?

감사!


다음과 같이 속성에서 열 순서를 지정할 수 있습니다.

public class MyEntity
{
    [Key, Column(Order=0)]
    public int MyFirstKeyProperty { get; set; }

    [Key, Column(Order=1)]
    public int MySecondKeyProperty { get; set; }

    [Key, Column(Order=2)]
    public string MyThirdKeyProperty { get; set; }

    // other properties
}

Finda 방법을 사용하는 경우 DbSet주요 매개 변수에 대해이 순서를 고려해야합니다.


Slauma가 제출 한 정답을 완료하려면 HasKey 메서드를 사용하여 복합 기본 키의 순서도 지정할 수 있습니다.

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

public class Ctp5Context : DbContext
{
    public DbSet<User> Users { get; set; }        

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>().HasKey(u => new 
        { 
            u.UserId, 
            u.Username 
        });
    }
}

If, like me, you prefer to use a configuration file you can do that in this way (based on Manavi's example):

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

public class UserConfiguration : EntityTypeConfiguration<User>
{
    public UserConfiguration()
    {
        ToTable("Users");
        HasKey(x => new {x.UserId, x.Username});
    }
}

Obviously you have to add the configuration file to your context:

public class Ctp5Context : DbContext
{
    public DbSet<User> Users { get; set; }        

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
         modelBuilder.Configurations.Add(new UserConfiguration());
    }
}

Use as a anonymous object:

modelBuilder.Entity<UserExamAttemptQuestion>().ToTable("Users").HasKey(o => new { o.UserId, o.Username }); 

참고URL : https://stackoverflow.com/questions/4950245/in-entity-framework-code-first-how-to-use-keyattribute-on-multiple-columns

반응형