2011-03-06 4 views
0

매개 변수가 -1이면 ID가 지정된 경우와 다른 쿼리를 실행해야합니다. 어떻게해야합니까? 나는 초기화 var q를 시도했다; If 블록 밖에 있지만 행운은 없습니다! 어떤 대답 당 내가 지금 가지고로서Linq 범위 문제 + 반복 코드 줄이기

// Loads by Entry ID, or if -1, by latest entry 
private void LoadEntryByID(int EntryID) 
{ 
    IEnumerable<tblBlogEntry> q; 
    if (EntryID == -1) 
    { 
     q = (
      from Blog in db.tblBlogEntries 
      orderby Blog.date descending 
      select new 
      { 
       Blog.ID, 
       Blog.title, 
       Blog.entry, 
       Blog.date, 
       Blog.userID, 
       Comments = (
        from BlogComments in db.tblBlogComments 
        where BlogComments.blogID == Blog.ID 
        select BlogComments).Count(), 
       Username = (
        from Users in db.yaf_Users 
        where Users.UserID == Blog.userID 
        select new { Users.DisplayName }) 
      }).FirstOrDefault(); 
    } 
    else 
    { 
     q = (
      from Blog in db.tblBlogEntries 
      where Blog.ID == EntryID 
      select new 
      { 
       Blog.ID, 
       Blog.title, 
       Blog.entry, 
       Blog.date, 
       Blog.userID, 
       Comments = (
        from BlogComments in db.tblBlogComments 
        where BlogComments.blogID == Blog.ID 
        select BlogComments).Count(), 
       Username = (
        from Users in db.yaf_Users 
        where Users.UserID == Blog.userID 
        select new { Users.DisplayName }) 
      }).SingleOrDefault(); 
    } 
    if (q == null) 
    { 
     this.Loaded = false; 
    } 
    else 
    { 
     this.ID = q.ID; 
     this.Title = q.title; 
     this.Entry = q.entry; 
     this.Date = (DateTime)q.date; 
     this.UserID = (int)q.userID; 
     this.Loaded = true; 
     this.AuthorUsername = q.Username; 
    }  
} 

내 주요 목표는 코드

편집

을 반복 줄이는 것입니다 :

// Blog data model 
public class EntryModel 
{ 
    public int ID { get; set; } 
    public string Title { get; set; } 
    public string Entry { get; set; } 
    public DateTime Date { get; set; } 
    public int UserID { get; set; } 
    public string Username { get; set; } 
    public int Comments { get; set; } 
} 

// A single blog entry 
public class BlogEntry 
{ 
    public bool Loaded;  // Did this entry load OK? 
    private DataClassesDataContext db = new DataClassesDataContext(); 
    public EntryModel ThisEntry = new EntryModel(); 

    // Initialisers 
    public BlogEntry(int EntryID) 
    { 
     this.LoadEntryByID(EntryID); 
    } 
    public BlogEntry() 
    { 
     this.LoadLatest(); 
    } 
    public void LoadLatest() 
    { 
     this.LoadEntryByID(-1); 
    }  

    // Loads by Entry ID, or if -1, by latest entry 
    private void LoadEntryByID(int EntryID) 
    { 
     EntryModel q = null; 
     if (EntryID == -1) 
     { 
      q = (from Blog in db.tblBlogEntries 
       orderby Blog.date descending 
       select new EntryModel 
       { 
        Title = Blog.title, 
        ID = Blog.ID, 
        Entry = Blog.entry, 
        Date = (DateTime)Blog.date, 
        UserID = (int)Blog.userID, 
        Comments = (from BlogComments in db.tblBlogComments where BlogComments.blogID == Blog.ID select BlogComments).Count(), 
        Username = (from Users in db.yaf_Users where Users.UserID == Blog.userID select new { Users.DisplayName }).SingleOrDefault().ToString() 
       } 
       ).FirstOrDefault(); 
     } 
     else 
     { 
      q = (from Blog in db.tblBlogEntries 
        where Blog.ID == EntryID 
        select new EntryModel 
        { 
         Title = Blog.title, 
         ID = Blog.ID, 
         Entry = Blog.entry, 
         Date = (DateTime)Blog.date, 
         UserID = (int)Blog.userID, 
         Comments = (from BlogComments in db.tblBlogComments where BlogComments.blogID == Blog.ID select BlogComments).Count(), 
         Username = (from Users in db.yaf_Users where Users.UserID == Blog.userID select new { Users.DisplayName }).SingleOrDefault().ToString() 
        }).SingleOrDefault(); 
     } 
     if (q == null) 
     { 
      this.Loaded = false; 
     } 
     else 
     {    
      this.ThisEntry.ID = q.ID; 
      this.ThisEntry.Title = q.Title; 
      this.ThisEntry.Entry = q.Entry; 
      this.ThisEntry.Date = q.Date; 
      this.ThisEntry.UserID = q.UserID; 
      this.Loaded = true; 
      this.ThisEntry.Username = q.Username; 
      this.ThisEntry.Comments = q.Comments; 
     }  
    } 
} 

이 작동하지만, 많이 던졌습니다 VS의 파란색 구불 구불 한 선들이 있으며,

this.ThisEntry.Username = q.Username; 
HTML에서

출력에 :

{표시 이름 = 톰}

다만 '톰'내가이 원하는대로!

+0

블록 외부에서 q를 IEnumerable 으로 다시 정의 하시겠습니까? – CarneyCode

+0

일반적인 참고로, 나는이 두 가지를 별개의 호출로 사용하고, if/else를 사용합니다. 그렇게 함으로 비즈니스 의미는 암시적인 "-1은 최신 항목을 의미합니다" – Larsbj

+0

이 아닌 나중에 명백하게 나타납니다.이 코드는 컴파일되지 않습니다. 익명 타입의'IEnumerable'을'IEnumerable '타입의 변수'q'에 할당하려고합니다. 더 나아가 (코드가 컴파일 된 경우)'q'는 항상 값을 가지기 때문에'this.Loaded = false; '라는 코드는 호출되지 않습니다. – Steven

답변

2
tblBlogEntry myBlog; 
if (EntryID != -1) 
{ 
    myBlog = db.tblBlogEntries 
      .SingleOrDefault(blog => blog.ID == EntryID); 
} 
else 
{ 
    myBlog = db.tblBlogEntries 
      .OrderByDescending(blog => blog.date).FirstOrDefault(); 
} 

this.Loaded = myBlog != null; 

if (this.Loaded) 
{ 
    this.ThisEntry = new EntryModel 
    { 
    ID = myBlog.ID, 
    Title = myBlog.title, 
    Entry = myBlog.entry, 
    Date = (DateTime)myBlog.date, 
    UserID = (int)myBlog.userID, 
    Username = db.yaf_Users 
       .Single(user => user.UserID == myBlog.userID).DisplayName, 
    Comments = db.tblBlogComments 
       .Where(comment => comment.blogID == myBlog.ID).Count() 
    } 
} 
+0

+1 반복 코드를 줄이기 위해. SingleOrDefault/FirstOrDefault를 사용하면'q'는'null'을 검사해야합니다. –

+0

굉장한 대답, 정확히 내가 무엇을 찾고 있었습니까 –

+0

당신을 진심으로 환영합니다. 필자는 LINQ 확장 메서드가 언어 구문보다 더 좋다고 생각합니다. 필자의 의견으로는이 코드가 더 깨끗한 코드로 작동하고 이것이 어떻게 작동하는지 더 잘 이해할 수 있기 때문입니다. – Jan

2

는 방식 t는 당신의 코드에 두 가지 문제가 있습니다

+0

CS0029 : 암시 적으로 'AnonymousType # 1'유형을 'tblBlogEntry'로 변환 할 수 없습니다. 나는 타입을 tblBLogEntry로 바꿨고 주석을위한 속성 필드에 Linq 디스플레이를 추가했지만 여기서 행운이 없다. 단지 반복 코드를 줄이려고했다. –

+0

C# 4를 사용하는 경우 @Tom.0 동적 인 것을 시도해 볼 수있을 것 같아 –

+0

질문을 업데이트했습니다 –

1

/ Loads by Entry ID, or if -1, by latest entry 
private void LoadEntryByID(int EntryID) 
{ 
    dynamic q = null; 
    if (EntryID == -1) 
    { 
     q = (from Blog in db.tblBlogEntries 
      orderby Blog.date descending 
      select new 
      { 
       Blog.ID, 
       Blog.title, 
       Blog.entry, 
       Blog.date, 
       Blog.userID, 
       Comments = (from BlogComments in db.tblBlogComments where BlogComments.blogID == Blog.ID select BlogComments).Count(), 
       Username = (from Users in db.yaf_Users where Users.UserID == Blog.userID select new { Users.DisplayName }).SingleOrDefault() 
      }).FirstOrDefault(); 
    } 
    else 
    { 
     q = (from Blog in db.tblBlogEntries 
       where Blog.ID == EntryID 
       select new 
       { 
        Blog.ID, 
        Blog.title, 
        Blog.entry, 
        Blog.date, 
        Blog.userID, 
        Comments = (from BlogComments in db.tblBlogComments where BlogComments.blogID == Blog.ID select BlogComments).Count(), 
        Username = (from Users in db.yaf_Users where Users.UserID == Blog.userID select new { Users.DisplayName }).SingleOrDefault() 
       }).SingleOrDefault(); 
    } 
    if (q == null) 
    { 
     this.Loaded = false; 
    } 
    else 
    { 
     this.ID = q.ID; 
     this.Title = q.title; 
     this.Entry = q.entry; 
     this.Date = (DateTime)q.date; 
     this.UserID = (int)q.userID; 
     this.Loaded = true; 
     this.AuthorUsername = q.Username.DisplayName; 
    }  
} 

}을보십시오. 첫째, 하나의 객체 만 선택하기 때문에 q를 IEnumerable로 선언하면 안됩니다. 범위를 선택한 경우 그렇게 할 수 있습니다.

둘째, 단일 tblBlogEntry 개체를 얻으므로 Q를 그런 식으로 선언해야하지만 익명 개체로 설정되어 있기 때문에 NEW를 사용하여 개체를 선택하면 안됩니다.이 경우 "CS0029: Cannot implicitly convert type 'AnonymousType#1' to 'tblBlogEntry'" error이 표시됩니다. tblBlogEntry로 선택해야합니다. 그러나 쿼리를 사용하여 전체 개체를 가져 오지 않거나 tblBlogEntry에없는 필드를 추가해야하는 경우 필요한 특성 만 가진 새 클래스를 만든 다음 새 개체를 만들 수 있습니다

ALL의 필드 으로 전체 개체를 가져 오는 : 그 클래스의 인스턴스 그냥 특정 필드를 가져 오는

// Loads by Entry ID, or if -1, by latest entry 
    private void LoadEntryByID(int EntryID) 
    { 
     tblBlogEntry q; 
     if (EntryID == -1) 
     { 
      q = (from Blog in db.tblBlogEntries 
       orderby Blog.date descending 
       select Blog).SingleOrDefault(); 
     } 
     else 
     { 
      q = (from Blog in db.tblBlogEntries 
        where Blog.ID == EntryID 
        select Blog).SingleOrDefault(); 
     } 
     if (q == null) 
     { 
      this.Loaded = false; 
     } 
     else 
     { 
      this.ID = q.ID; 
      this.Title = q.title; 
      this.Entry = q.entry; 
      this.Date = (DateTime)q.date; 
      this.UserID = (int)q.userID; 
      this.Loaded = true; 
      this.AuthorUsername = q.Username; 
     }  
    } 
} 

, 또는 객체 나던이 필드 :

public class EntryModel 
{ 
    public int ID {get;set;} 
    public string Title {get;set;} 
    public string Entry{get;set;} 
    public DateTime Date {get;set;} 
    public int UserID {get;set;} 
    public List<Comment> Comments {get;set;} 
} 
// Loads by Entry ID, or if -1, by latest entry 
private void LoadEntryByID(int EntryID) 
{ 
    EntryModel q; 
    if (EntryID == -1) 
    { 
     q = (from Blog in db.tblBlogEntries 
     orderby Blog.date descending 
     select select new EntryModel() 
     { 
      ID=Blog.ID, 
      Title=Blog.title, 
      Entry=Blog.entry, 
       Date=Blog.date, 
       UserId=Blog.userID, 
       Comments = (from BlogComments in db.tblBlogComments where  BlogComments.blogID == Blog.ID select BlogComments).Count() 
      }).SingleOrDefault(); 
     } 
     else 
     { 
      q = (from Blog in db.tblBlogEntries 
        where Blog.ID == EntryID 
        select select new EntryModel() 
      { 
       ID=Blog.ID, 
       Title=Blog.title, 
       Entry=Blog.entry, 
       Date=Blog.date, 
       UserId=Blog.userID, 
       Comments = (from BlogComments in db.tblBlogComments where  BlogComments.blogID == Blog.ID select BlogComments).Count() 
      }).SingleOrDefault(); 
     } 
     if (q == null) 
     { 
      this.Loaded = false; 
     } 
     else 
     { 
      this.ID = q.ID; 
      this.Title = q.title; 
      this.Entry = q.entry; 
      this.Date = (DateTime)q.date; 
      this.UserID = (int)q.userID; 
      this.Loaded = true; 
      this.AuthorUsername = q.Username; 
     }  
    } 
} 
+0

안녕하세요, 답변 주셔서 감사합니다.이 방법이 마음에 듭니다. John Skeet이 비슷한 것을 추천했다고 생각합니다. 그래도 내 답변을 업데이 트했습니다, 나는 파란 구불 구불 한 라인을 많이 받고 또한 사용자 이름이 제대로 렌더링되지 않습니다. –

+0

UserName은 어떤 유형입니까? 왜 그것은 단지 문자열이 아니므로 linq 쿼리를 할 때 새로운 Username 클래스를 만드는 대신 값을 선택하면됩니까? –