2017-03-21 4 views
0

나는 MVC5 모델에서 자기 참조 모델을 만들고있다. 이 모델은 다음과 같습니다 :자기 참조 MVC5 EF6 데이터베이스에 새 ID 생성

public class GalleryCat 
    { 
    [Key] 
    public int GalleryCatId { get; set; } 
    public string CatName {get; set;} 
    public virtual GalleryCat GalleryCatParent { get; set; } 
    public int GalleryCatParentId {get; set; } 
    public virtual ICollection<GalleryCat> Children { get; set; } 
    public virtual ICollection<Gallery> Galleries { get; set; } 

    protected void OnModelCreating (DbModelBuilder modelBuilder) 
     { 
      modelBuilder.Entity<GalleryCat>() 
      .HasOptional(c => c.GalleryCatParent) 
      .WithMany(c => c.Children) 
      .HasForeignKey(p => p.GalleryCatParentId); 

     } 
} 

이 GalleryCatParent_GalleryCatId 대신 GalleryCatParentId로 MySQL 데이터베이스에 새로운 ID 필드를 생성? 누군가 내가 잘못하고있는 것을 인도 할 수 있습니까?

답변

0

OnModelCreatingDbContext의 방법입니다. 모든 엔티티 클래스에 추가 할 수는 없습니다. 즉, 유창한 구성이 실제로 실행되지 않으므로 설치 프로그램이 데이터베이스에 적용되지 않습니다.

어느 당신의 맥락에서 OnModelCreating을 무시하고이이 유창 설정을 추가하거나 엔티티로 설정을 유지하려는 경우, 당신은을 통해 그렇게 할 수처럼 맥락에서

public class GalleryCat 
{ 
    ... 

    public class Config : EntityTypeConfiguration<GalleryCat> 
    { 
     public Config() 
     { 
      HasOptional(c => c.GalleryCatParent) 
       .WithMany(c => c.Children) 
       .HasForeignKey(p => p.GalleryCatParentId); 
     } 
    } 
} 

그런 다음, OnModelCreating를 오버라이드 (override) 그래서 :

+0

이 오류가 발생하면 감사합니다.이 오류가 발생합니다 .Migrations.ApplicationUserLogin :: EntityType 'ApplicationUserLogin'에 정의 된 키가 없습니다. 이 EntityType의 키를 정의하십시오. – Diin

+0

그건 전혀 상관없는 문제입니다. 그 오류는 꽤 명백합니다. 언급 된 엔티티에 정의 된 키가 없습니다. 클래스 이름을 기반으로하면 IdentityUserLogin에서 상속하는 것을 거의 무시했을 것입니다. –

+0

누구나 비슷한 문제가 생기면 identityconfig protected override에 추가하십시오. void OnModelCreating (DbModelBuilder modelBuilder) { modelBuilder.Configurations.Add (new GalleryCat.Config()); modelBuilder.Entity (). HasKey (l => l.UserId); modelBuilder.Entity (). HasKey (r => r.RoleId); modelBuilder.Entity (). HasKey (r => 새 {r.RoleId, r.UserId}); } – Diin