Reputation:
I currently have a LINQ query written in one my controllers that I want to return a single blog post (based off a model) with corresponding comments and topics.
This is what I currently have as my query which I used to return a list of all my blog posts for the home page. I added "where p.id == id (which is the parameter taken in by the ActionResult to fetch the correct post.
var post = from p in db.Set<BlogPost>()
where p.id == id
select new PostViewModel
{
Id = p.id,
Title = p.Title,
DateCreated = p.DateCreated,
Content = p.Content,
Topics = p.Topics,
Comments = p.Comments,
CommentCount = p.Comments.Count
};
return View(post);
The return currently is sending an IQueryable when I just want it to be a single post. Currently I have a foreach in my razor view which is useless and wrong but it works. How can I change this to do what I want?
Upvotes: 1
Views: 1433
Reputation: 1019
replace your LINQ with this
var post = (from p in db.Set<BlogPost>()
where p.id == id
select new PostViewModel
{
Id = p.id,
Title = p.Title,
DateCreated = p.DateCreated,
Content = p.Content,
Topics = p.Topics,
Comments = p.Comments,
CommentCount = p.Comments.Count
}).FirstOrDefault();
Upvotes: 0
Reputation: 67075
Just do post.First()
that should do the trick. Really any function that produces a concrete value will work. First
, FirstOrDefault
, Single
, SingleOrDefault
, ToList
, or ToArray
I have included the links to each method so you can see what works for you. It sounds like you will want a First or Single variation, depending on if you want errors if more than one post is pulled
Upvotes: 1
Reputation: 22555
You can do:
return View(post.SingleOrDefault());
Or if you want to have an exception in the case list is empty:
return View(post.Single());
Upvotes: 2
Reputation: 838276
It sound like you want to use First or Single:
return View(post.Single());
The difference between them is that Single
will throw an exception if more than one matching row is found.
Upvotes: 1
Reputation: 160902
Just add First()
or Single()
(which one is right for you depends on context) to your query:
return View(post.First());
Upvotes: 1