2017-09-29 6 views
2

.NET Core 2.0을 사용하고 있습니다. 나는이 시간에 EF 코어에서 자동 게으른 로딩을 지원하지 않는다는 것을 알고있는 네비게이션 속성에 대해 많이 썼다. 나는 탐색 속성을 만들기 위해 Microsoft의 접근 방식을 사용하고 있습니다. 나는 다 - 많은 관계를 만들려고 노력하고 있습니다.EF 코어에서 사용자 정의 탐색 속성을 만드는 방법

먼저 수동으로 매핑 테이블에서 새 개체를 추가 할 때 또한 OnModelCreating 클래스

  builder.Entity<ProductCategory>() 
      .HasKey(x => new { x.CategoryId, x.ProductId }); 

      builder.Entity<ProductCategory>() 
       .HasOne(x => x.Product) 
       .WithMany(x => x.ProductCategory) 
      .HasForeignKey(x => x.ProductId); 

      builder.Entity<ProductCategory>() 
       .HasOne(x => x.Category) 
       .WithMany(x => x.ProductCategory) 
      .HasForeignKey(x => x.CategoryId); 

에서

public class ProductCategory 
    { 
     [Key] 
     public int ProductId { get; set; } 
     [ForeignKey("ProductId")] 
     public virtual Product Product { get; set; } 

     [Key] 
     public int CategoryId { get; set; } 
     [ForeignKey("CategoryId")] 
     public virtual Category Category { get; set; } 
    } 

public class Product 
    { 
     public int Id { get; set; } 
     public virtual ICollection<ProductCategory> ProductCategory { get; set; 
    } 

    public class Category 
    { 
     public int Id { get; set; } 
     public virtual ICollection<ProductCategory> ProductCategory { get; set; 
    } 

새로운 DbSet

처럼 ApplicationDbContext에 포함 된 매핑 테이블을 만듭니다.

var productCategory = new ProductCategory 
      { 
       CategoryId = 1, 
       ProductId = 1 
      }; 

      db.ProductCategory.Add(productCategory); 
      db.SaveChanges(); 

항목은 그 후 것은 table.You가 난`카테고리에서 제품에 액세스하려고 예를 볼 수 있습니다 탐색 속성을 테스트 할 제품 또는 카테고리에 액세스하려고하지만 매핑 만 현재 클래스를 수신, 성공적으로 추가 클래스 :

model.Categories = this._categoryService 
       .All() 
       .Include(x => x.ProductCategory) 
       .ToList(); 

many-to-many-error-ef7

Product 클래스가 null?

답변

2

네비게이션 속성에 자동으로 역 네비게이션 속성이 포함되어 있기 때문입니다. ThenInclude을 사용하여 구체적으로 요청해야합니다. 이것은 또한 자동으로 (부하)을 Product 기업의 ProductCategory 컬렉션 속성을 포함 할 것

model.Categories = this._categoryService 
       .All() 
       .Include(x => x.ProductCategory) 
        .ThenInclude(x => x.Product) 
       .ToList(); 

참고 : All 방법을 가정

이 같은 IQueryable<Category>, 뭔가를 반환합니다.

+0

ProductCategory가 열거 형이고 lambda의 x가 열거 형이기 때문에 .ThenInclude (x => x.Product)를 추가 할 수 없습니다. 나는 또한 시도했다 .TinInclude (x => x.Select (x => x.Product)),하지만 여전히 작동하지 않습니다! –

+1

@DTodorov 당신이 시도한 것은 EF6입니다. 위의 작품, 그냥 VS Intellisense 알려진 문제가 있습니다. 'ThenInclude'에는 코일 선택과 참조를위한 두 가지 과부하가 있습니다. https://stackoverflow.com/questions/45658411/ef-core-second-level-theninclude-missworks/45658984#45658984 –

+1

무엇이 ... 지금은 잘 작동합니다. 고마워요! –