简体   繁体   中英

What exactly should a model contain in MVC?

I've recently been reading Microsoft's tutorial on ASP.NET Core and seen that the controller classes of that tutorial include LINQ queries to fetch data from a database. A code snippet of that tutrorial for example looks like this:


// GET: Movies
public async Task<IActionResult> Index(string movieGenre, string searchString)
{
    // Use LINQ to get list of genres.
    IQueryable<string> genreQuery = from m in _context.Movie
                                    orderby m.Genre
                                    select m.Genre;

    var movies = from m in _context.Movie
                 select m;

    if (!string.IsNullOrEmpty(searchString))
    {
        movies = movies.Where(s => s.Title.Contains(searchString));
    }

    if (!string.IsNullOrEmpty(movieGenre))
    {
        movies = movies.Where(x => x.Genre == movieGenre);
    }

    var movieGenreVM = new MovieGenreViewModel
    {
        Genres = new SelectList(await genreQuery.Distinct().ToListAsync()),
        Movies = await movies.ToListAsync()
    };

    return View(movieGenreVM);
}

My question is the following: What exactly does a model class contain? In all the articles I read about MVC pattern I am advised to put the functions where I fetch data from a database into a model class. So are they doing a mistake in this tutorial?

A model class is a DTO and you can read more about them here: https://docs.microsoft.com/en-us/aspnet/web-api/overview/data/using-web-api-with-entity-framework/part-5

There is not an error in the code that you have, it is only a bad practice. The main difference between an entity and a DTO is that you do not mention the relation to another DTO. For example, when we talk about Entities we have

public class Author{
public string name{get; set;}
public List<Book> Books {get; set;}
}

But when we talk about DTO we will have only

public class Author{
    public string name{get; set;}
    }

The code will run but you do not want to get the whole properties of the entity, only a few and clearly not the entities related to it. If you do the version they presented, the code will take more to compile and will be prone to error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM