I'm writing a simple MVC app to learn about ASP.NET MVC. I'm following the Pluralsight courses and they've been a great help. However, I'm still a bit in the dark when it comes to LINQ.
I have a piece of working code, and I'd like to know if it could be improved or be made more concise.
What it needs to do:
Currently, I have two ways of doing this, which both work:
var board =
db.Boards
.Where(b => b.Id == id)
.Select(b => new BoardViewModel {
Title = b.Title
})
.First();
And method 2:
var board =
db.Boards
.Find(id);
BoardViewModel model = new BoardViewModel();
model.Title = board.Title;
What I'm mostly wondering about, in a query where I request multiple results, I'm able to assign the values to a ViewModel using a lambda expression in the Select extension method, can I use something similar in the query where I'm using the Find method?
For example, something that would look like this:
var board =
db.Boards
.Select(b => new BoardViewModel {
Title = b.Title
}
.Find(id);
I'm very interested in what other ways there are on approaching this.
Something like this? Assuming you're expecting one record with the given id.
var board = db.Boards.Select(b => new BoardViewModel
{
Title = b.Title
}).FirstOrDefault(b => b.Id == id)