1

毫无疑问,我知道控制器和模型的用途。但是,我能够编写与我的数据库交互的代码,例如在控制器或模型上将用户添加到表中。我应该在什么时候在控制器和模型中编写代码?尽管两者都有效,但哪种方式更有条理或更实用。如果答案模棱两可,您能否发布示例?谢谢

4

3 回答 3

5

For that, you should add a logic layer or logic classes. The controller should determine wants to do and can do, shuffle them in the right direction (logic layer), then determine what to show the user after the logic. Putting the logic in a separate layer will help keep your controllers lean and promote code reuse.

In the domain core, we only have models with properties. All logic is performed in a different layer, except for things like a property that returns fields concatenated in a format.

于 2013-08-16T22:14:47.603 回答
4

访问数据库的代码应该在服务层而不是保存在控制器或模型中。

从控制器访问数据库实体

这是我对上述问题的回答,您还可以阅读其他答案,为什么您应该保留在单独的层中。

namespace MyProject.Web.Controllers
{
   public class MyController : Controller
   {
      private readonly IKittenService _kittenService ;

      public MyController(IKittenService kittenService)
      {
         _kittenService = kittenService;
      }

      public ActionResult Kittens()
      {
          // var result = _kittenService.GetLatestKittens(10);
          // Return something.
      }
   }  
}

namespace MyProject.Domain.Kittens
{
   public class Kitten
   {
      public string Name {get; set; }
      public string Url {get; set; }
   }
}

namespace MyProject.Services.KittenService
{
   public interface IKittenService
   {
       IEnumerable<Kitten> GetLatestKittens(int fluffinessIndex=10);
   }
}

namespace MyProject.Services.KittenService
{
   public class KittenService : IKittenService
   {
      public IEnumerable<Kitten> GetLatestKittens(int fluffinessIndex=10)
      {
         using(var db = new KittenEntities())
         {
            return db.Kittens // this explicit query is here
                      .Where(kitten=>kitten.fluffiness > 10) 
                      .Select(kitten=>new {
                            Name=kitten.name,
                            Url=kitten.imageUrl
                      }).Take(10); 
         }
      }
   }
}
于 2013-08-16T22:13:04.860 回答
3

ASP.NET MVC和MVC,一般来说,是一种表示层模式;因此,您与数据库的交互应该在表示层之外的层中,通常是数据访问层,但它也可以是服务层或业务层。

于 2013-08-16T22:19:49.787 回答