Search code examples
c#asp.net-mvclinqasp.net-mvc-viewmodel

Using a lambda expression to assign data to a ViewModel in a query using .Find()


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:

  1. Extract data from my DB based on the given id (which is the primary key)
  2. Create a new BoardViewModel(), assigning only the Title
  3. Return an instance of BoardViewModel, with the Title property set

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.


Solution

  • 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)