2013-08-21 3 views
0

내가 이전에 성공적으로 과정 내에서 관련 하위 섹션의 목록을 반환 한 내 AdminController 내에서 다음 코드 줄을했다 컨트롤러는 dbcontext를 호출하는 것이 좋지 않았으므로 이것을 AdminViewModel로 옮겼습니다. 내 AdminViewModel 내에서 변수가 있습니다 공개 목록 CourseSectionList {get; 세트; } 그리고이 변수에 JSON 요청 세부 정보를 채우려고합니다. 다음과 같이 내 코드는 다음과 같습니다채우기 IEnumberable <class>이

AdminViewModel

public void GetCourseSectionDetails(int courseID) 
{ 
    var Sections = dbcontext.CourseSection.Where(cs => cs.CourseID.Equals(courseID)).Select(x => new CourseSection 
    { 
    CourseSectionID = x.CourseSectionID, 
    Title = x.Title 
    }); 
    this.CourseSectionList = Sections.ToList(); 
} 

AdminController

[AcceptVerbs(HttpVerbs.Get)] 
public JsonResult GetCourseSections(int courseID) 
{ 
    avm.GetCourseSectionDetails(courseID); 
    var Sections = avm.CourseSectionList.Where(cs => cs.CourseID.Equals(courseID)).Select(x => new 
    {    
    sectionID = x.CourseSectionID, 
    sectionTitle = x.Title 
    }); 
    System.Diagnostics.EventLog.WriteEntry("Application", "JSON=" + Sections.ToList(), System.Diagnostics.EventLogEntryType.Error); 
    return Json(Sections, JsonRequestBehavior.AllowGet); 
} 

나는 오류 엔티티 또는 복합 형 'MetaLearning.Data.CourseSection'을 얻고있다 할 수 없다 LINQ to Entities 쿼리에서 생성됩니다. 섹션을 사용하여 this.CourseSectionList 변수를 채우려면 어떻게해야합니까?

답변

2

: 컨트롤러가 의존성으로 저장소를 가지고 있습니다

public class RepositoryEF : IRepository 
{ 
    public IList<CourseSection> GetSections(int courseID) 
    { 
     using (ctx = new YourDbContextHere()) 
     { 
      return ctx 
       .CourseSection 
       .Where(cs => cs.CourseID.Equals(courseID)) 
       .Select(x => new CourseSection 
       { 
        CourseSectionID = x.CourseSectionID, 
        Title = x.Title, 
       }) 
       .ToList(); 
     } 
    } 
} 

마지막 :

public interface IRepository 
{ 
    public IList<CourseSection> GetSections(int courseID); 
} 

구현 될 것이다 : 나는 당신이 특정 DAL 층을 갖는 것이 좋습니다 오류 메시지는 linq to entities에서

.Select(m => new <Entity>{bla bla}) 
를 사용할 수 없습니다.

여기서 <Entity> ...은 모델의 엔티티 중 하나입니다.

는 그러니 당신은 당신이 필요로하는 속성을 가진 '비 모델 "클래스 (DTO)를 사용하거나 (linq to objects 그 제한을하지 않았기 때문에)

.ToList() 
.Select(m => new <Entity>{bla bla}); 

당신은 찾을 수 있습니다 선택하기 전에 열거해야 그것은 할 수없는 이유의 멋진 설명 here

편집 : 당신이 싶어 당신의 엔티티의 일부 속성을 가져 오지하고 싶지는 DTO를 사용하지 않는 경우 당신은 또한, 같은 일을 할 수

:

return ctx 
     .CourseSection 
     .Where(cs => cs.CourseID.Equals(courseID)) 
     //use an anonymous object to retrieve only the wanted properties 
     .Select(x => new 
       { 
        c= x.CourseSectionID, 
        t= x.Title, 
       }) 
     //enumerate, good bye linq2entities 
     .ToList() 
     //welcome to linq2objects 
     .Select(m => new CourseSection { 
        CourseSectionID = m.c, 
        Title = m.t, 
      }) 
      .ToList(); 
0

컨트롤러에서 동일한 코드를 반복하지 않아도되지만보기에 직접 목록을 전달하십시오.

이것은 데이터 액세스 코드를 뷰 모델에 배치하는 것이 컨트롤러에 유지하는 것보다 훨씬 나쁜 습관이라고 전합니다. 에 의해 지적

public class SomeController : Controller 
{ 
    private readonly IRepository repo; 
    public SomeController(IRepository repo) 
    { 
     this.repo = repo; 
    } 

    [AcceptVerbs(HttpVerbs.Get)] 
    public ActionResult GetCourseSections(int courseID) 
    { 
     var sections = this.repo.GetSections(courseID); 
     return Json(sections, JsonRequestBehavior.AllowGet); 
    } 
} 
+0

내가 생각하지 않는 주소를 자신의 오류. – asymptoticFault

+1

그래도 좋은 리팩토링 추천. – asymptoticFault

+1

하지만 모델의 엔티티에 투영 할 수는 없습니다 ... –

0

가이드로 대린의 답변을 사용하여 다음과 같이 내가 이런 짓을 :

뷰 모델

public void GetCourseSectionDetails(int courseID) 
    { 
     this.CourseSectionList = dbcontext.CourseSection.AsEnumerable().Where(cs => cs.CourseID.Equals(courseID)).Select(x => new CourseSection 
     { 
      CourseSectionID = x.CourseSectionID, 
      Title = x.Title 
     }).ToList(); 
    } 

컨트롤러

[AcceptVerbs(HttpVerbs.Get)] 
    public JsonResult GetCourseSections(int courseID) 
    {    
     var sections = avm.CourseSectionList; 
     return Json(sections, JsonRequestBehavior.AllowGet); 
    } 
관련 문제