在MVC模型数据库查询 [英] Database Queries in MVC Model

查看:179
本文介绍了在MVC模型数据库查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个MVC项目,如果我把 LINQ 模式查询,是对MVC模式?

 命名空间DocLibrary.Models
{
    公共类作者
    {
        私人DocLibraryContext DB =新DocLibraryContext();        [键]
        公众的Int32 AUTHORID {搞定;组; }        [StringLength(20)]
        公共字符串名称{;组; }        ..        公共字符串GetNameById(INT AUTHORID)
        {
            VAR查询从在db.Author =
                        其中,a.AuthorId == AUTHORID
                        选择a.Name;            返回query.FirstOrDefault();
        }
        公共作者GetAuthorById(INT AUTHORID)
        {
            VAR查询从在db.Author =
                        其中,a.AuthorId.Equals(AUTHORID)
                        选择一个;            返回query.FirstOrDefault();
        }
    }

或者我应该将这些方法( GetNameById GetAuthorById )来控制?


解决方案

  

在一个MVC项目,如果我把LINQ查询的型号,它是对MVC模式?


没有,这不是对MVC模式。数据库查询在模型完美的罚款。显然,应明确区分型号和要传递给你的看法视图模型之间进行。视图模型不应该包含任何数据库的具体的东西。


  

或者我应该将这些方法(GetNameById,GetAuthorById)到控制器?


绝对不是。该控制器的责任不是查询数据库。控制器的责任是交谈的模式,建立一个视图模型,并通过该视图模型到视图。控制器甚至不应该知道数据库是什么。

In a MVC project if I put LINQ queries in Model, is it against the MVC Pattern?

namespace DocLibrary.Models
{
    public class Author
    {
        private DocLibraryContext db = new DocLibraryContext();

        [Key]
        public Int32 AuthorId { get; set; }

        [StringLength(20)]
        public String Name { get; set; }

        ..

        public string GetNameById(int AuthorId)
        {
            var query = from a in db.Author
                        where a.AuthorId == AuthorId
                        select a.Name;

            return query.FirstOrDefault();
        }


        public Author GetAuthorById(int AuthorId)
        {
            var query = from a in db.Author
                        where a.AuthorId.Equals(AuthorId)
                        select a;

            return query.FirstOrDefault();
        }
    }

Or should I move these methods (GetNameById, GetAuthorById) to Controller?

解决方案

In a MVC project if I put LINQ queries in Model, is it against the MVC Pattern?

No, it's not against the MVC pattern. Database queries are perfectly fine in the Model. Obviously a clear distinction should be made between the Model and the View Model that you are passing to your views. The view model should not contain any database specific stuff.

Or should I move these methods (GetNameById, GetAuthorById) to Controller?

Absolutely not. The controller's responsibility is not to query a database. A controller responsibility is to talk to the Model, build a view model and pass this view model to the view. A controller shouldn't even know what a database is.

这篇关于在MVC模型数据库查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆