2013-08-28 1 views
0

내가 엔티티 프레임 워크와 MVC 프로젝트를 개발하고 또 다른 클래스에 캐스트와 나는 같은 카테고리 테이블이 있습니다C#을 재귀 ​​

public partial class Categories 
{ 
    public Categories() 
    { 
     this.Categories1 = new HashSet<Categories>(); 
    } 

    public int CategoryId { get; set; } 
    public string CategoryName { get; set; } 
    public Nullable<int> RelatedCategoryId { get; set; } 

    public virtual ICollection<Categories> Categories1 { get; set; } //Children 
    public virtual Categories Categories2 { get; set; } //Parent 
} 

내가 EF 테이블의 데이터를 얻을, 그것은 나에게 내가 원하는 객체를 제공합니다 . 자녀가있는 부모.

class Program 
    { 
     static Entities db = new Entities(); 

     static void Main(string[] args) 
     { 
      List<Categories> categories = db.Categories.Where(item => item.RelatedId == null).ToList(); 
     } 
} 

relatedId == null 부분에는 상위가없는 주요 카테고리가 있습니다.

여기까지는 문제가 없습니다. 하지만 난 EF 또 다른 클래스로 돌아 categories 개체를 캐스팅 할 :

public class NewCategories 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 

    private List<NewCategories> _subCategories; 

    public NewCategories() 
    { 
     _subCategories= new List<NewCategories>(); 
    } 

    public List<NewCategories> SubCategories { get { return _subCategories; } } 
} 

을 그리고 난 새로운 List<NewCategories> newCategories 객체를 원한다.

어떻게 수행 할 수 있습니까?

감사합니다.

+0

당신이 넣어 무엇을 하시겠습니까? '하위 카테고리'에? –

+0

'List categories' 객체와 동일한 논리입니다. 나는 관련 아이디가 동등한 부모 인 Id를두기를 원합니다. 마찬가지로 나는'List '에'List '을 던지기를 원한다고 말했다. – ergunysr

+0

'List '를 얻으려면 ** select **를 사용하여 ** 프로젝트 **를 수행해야하며'NewCategories'의 인스턴스를'Categories'에서 초기화해야합니다. 'Categories'에서 유추 할 수 있지만'SubCategories'는 질문입니다. 'Categories'에서'NewCategories'의'SubCategories'에'Categories1'을 넣거나 매핑하고 싶습니다. –

답변

1

난 당신이 NewCategories, 이런 일에 Categories을 변환하는 recursive 방법을 만들 생각 (작동하는지 잘 모르겠어요,하지만 그것은 시도 가치) :

public NewCategories ConvertToNewCategories(Categories cat){ 
    NewCategories nc = new NewCategories {Id = cat.CategoryId, Name = cat.CategoryName}; 
    nc.SubCategories.AddRange(cat.Categories1.Select(c=>ConvertToNewCategories(c))); 
    return nc; 
} 
//Then 
List<NewCategories> categories = db.Categories.Where(item => item.RelatedId == null) 
               .Select(item=>ConvertToNewCategories(item)) 
               .ToList(); 
+0

답변 해 주셔서 감사합니다. 이와 같이 사용하면 'LINQ to Entities'메서드가 'GeneralTestProject.Categories ConvertToNewCategories (Test.Data.Categories)'메서드를 인식하지 못하고이 메서드를 저장소 식으로 변환 할 수 없습니다. '그러나이 메서드를 사용하면'db .Categories.Where (item => item.RelatedId == null) .ToList();'완벽하게 작동했습니다 :) Thanks a lot !!! – ergunysr

+0

@ergunysr'EF'를 사용하는 것에 대해 눈치 채지 못했습니다. 나는'LINQ-to-SQL' (그리고 물론'LINQ-to-Object')에서 작동 할 것이라고 확신합니다. –