shapper wrote:
Quote:
I am using the following:
>
PostPaper paper = (from p in database.Posts
where p.PostID == id
select new PostPaper {
Post = p,
Tags = (from pt in database.PostsTags
join t in database.Tags on pt.TagID
equals t.TagID
where pt.PostID == id
orderby t.Name
select t).ToList()
}).SingleOrDefault();
>
While this will work just fine, you may want to consider using the designer
to generate entity sets and associations. This will take care of the joins
for you, allowing you to write much more concise code:
from p in database.Posts
where p.PostID == id
select new PostPaper ( Post = p, Tags = p.Tags.OrderBy(t =>
t.Name).ToList() };
Consult the help for more information on associations.
Quote:
PostPaper has also another property named TagsCSV which is the same
has Tags but in a CSV format so I have:
>
paper.TagsCSV = string.Join(", ", paper.Tags.Select(t =>
t.Name).ToArray());
>
The problem is that sometimes in also get a list of papers:
>
viewData.PostsPapers = (from p in database.Posts
orderby p.UpdatedAt descending
where p.IsPublished == true
select new PostPaper {
Post = p,
Tags = (from pt in database.PostsTags
join t in database.Tags on
pt.TagID equals t.TagID
where pt.PostID == p.PostID
orderby t.Name
select t).ToList()
}).ToPagedList(page.HasValue ?
page.Value - 1 : 0, PageSize);
>
Where PostPapers is an IPagedList<PollPaper>.
>
How can I create the TagsCSV for each PostPaper in viewData
PostPapers?
>
I tried to integrate the TagsCSV creation in select new PostPaper but
I wasn't able to do.
>
Again, the continuous selecting of tags belonging to posts suggests you want
an automatically managed entity set for that. You can do without, though:
from p in database.Posts
...
let tags = (from pt in database.PostTags...
let tagsCsv = string.Join(", ", tags.Select(t =t.Name).ToArray());
select new PostPaper { Post = p, Tags = tags.To, TagsCSV =
tagsCsv.ToArray }...
The "let" clause allows you to store arbitrary intermediate results. It's
very convenient for enhancing the readability of big queries like these.
--
J.