Linq Scope Problem + Reduce Repeated Code
Posted
by
Tom Gullen
on Stack Overflow
See other posts from Stack Overflow
or by Tom Gullen
Published on 2011-03-06T15:33:48Z
Indexed on
2011/03/06
16:10 UTC
Read the original article
Hit count: 224
If the parameter is -1, it needs to run a different query as to if an ID was specified... how do I do this? I've tried initialising var q; outside the If block but no luck!
// 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;
}
}
My main aim is to reduce repeating code
© Stack Overflow or respective owner