반응형
엔터티 프레임 워크 코드에서 먼저 여러 열에 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
}
Find
a 의 방법을 사용하는 경우 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 });
반응형
'developer tip' 카테고리의 다른 글
AWS SNS를 사용한 FCM (0) | 2020.09.07 |
---|---|
많은 정적 메서드를 사용하는 것이 나쁜가요? (0) | 2020.09.07 |
두 개체를 비교하고 차이점 찾기 (0) | 2020.09.07 |
new Date ()는 Chrome과 Firefox에서 다르게 작동합니다. (0) | 2020.09.06 |
Android, 다른 앱이 실행될 때 감지 (0) | 2020.09.06 |