如何将此代码转换为服务模式



这是我的代码:

        [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无法返回列表。

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
}

在注释中的对话之后,您可能应该创建一个类来保存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...
 }

最新更新