【问题标题】:How to convert this code to service pattern?如何将此代码转换为服务模式?
【发布时间】:2018-06-12 22:12:33
【问题描述】:

这是我的代码:

        [HttpGet]
    public ActionResult GetCategor(int catId)
    {
      using (uuEntities ems = new uuEntities())
      {
        return Json(ems.SupportSubCats.Where(x => x.CatID == catId).Select(
        x => new
        {
          SubId = x.SubCatID,
          SUbName = x.SubCatName
        }).ToList(), JsonRequestBehavior.AllowGet);
      }
    }

我尝试过的:

在控制器中:

   [HttpGet]
    public ActionResult GetCategor(int catId)
    {
        return Json(_service.List(int catId), JsonRequestBehavior.AllowGet);
      }
    } 

服务中:

    public void List(int catId)
    {
      return new GenericRepository<SupportSubCategory>(_factory.ContextFactory)
        .Get(filter: (x => x.CatID == catId))
        .Select(x => new
        {
          SubId = x.SubCatID,
          SUbName = x.SubCatName
        }).ToList();
    }

我认为我的返回类型不正确,请建议我解决方案。在公共 void 附近,我收到 void 无法返回列表的错误。

【问题讨论】:

    标签: .net model-view-controller service


    【解决方案1】:

    void 方法不会向其调用者返回任何值。 您可以在 void 方法中使用空的 return 仅用于退出该方法 - 但您不能返回任何值。

    此代码完全有效,并被广泛用作一种常见做法:

    public void DoSomething()
    {
        if(<someCondition>)
        {
            return;
        }
        // The rest of the code will only be executed if <someCondition> evalualtes to false
    }
    

    通常,当您将参数传递给方法并且需要在实际执行方法的其余部分之前验证它们时,您会使用此模式。

    但是,此代码无效并且无法编译

    public void DoSomething()
    {
        if(<someCondition>)
        {
            return false; // Here is your compiler error...
        }
        // The rest of the code will only be executed if <someCondition> evalualtes to false
    }
    

    根据我们在 cmets 中的对话,您可能应该创建一个类来保存 Select 的结果,而不是使用匿名类型,并从您的方法中返回该类的列表:

    // Note: I've renamed your method to something a little bit more meaningful
    public List<SubDetails> ListSubDetails(int catId) 
    {
      return new GenericRepository<SupportSubCategory>(_factory.ContextFactory)
        .Get(filter: (x => x.CatID == catId))
        .Select(x => new SubDetails()
        {
          SubId = x.SubCatID,
          SUbName = x.SubCatName
        }).ToList();
    }
    

    ...

    public class SubDetails
    {
        public Int SubId {get; set;} // I'm guessing int here...
        public string SUbName {get; set;} // I'm guessing string here...
     }
    

    【讨论】:

    • 使用带 null 的简单返回,它在控制器中给出错误:“无法将 void 转换为对象”靠近 catId
    • 是的,因为null 是一个没有设置为任何对象的引用。如果您在void 方法中使用return,则只能这样使用:return;。其他一切都会产生编译器错误。
    • 那我应该用什么来代替 void ?
    • 我在控制器中的第一个代码正在工作..但是现在,我正在使用服务,所以我想在服务中使用该逻辑并将其调用给控制器...请建议我解决它的方法跨度>
    • 您不应该从该方法返回任何内容,或者使用SubIdSUbName 创建一个类型并选择它而不是您的匿名类型,然后返回该类型的列表。跨度>
    猜你喜欢
    • 1970-01-01
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多