如何将此代码转换为服务模式? [英] How to convert this code to service pattern?
问题描述
这是我的代码:
[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无法返回列表.
I think my return type is incorrect please suggest me the solution. Near public void, i am getting an error that void can not return the list.
推荐答案
void
方法不会向其调用方返回任何值.
您只能在void
方法中使用空的return
来退出该方法-但不能返回任何值.
A void
methods does not return any value to it's caller.
You can use an empty return
in a void
method only to exit the method - but you can't return any value.
此代码是完全有效的,并已广泛用作惯例:
This code is perfectly valid and widely used as a common practice:
public void DoSomething()
{
if(<someCondition>)
{
return;
}
// The rest of the code will only be executed if <someCondition> evalualtes to false
}
通常,在将参数传递到方法中时需要使用此模式,并且需要在实际执行方法的其余部分之前对其进行验证.
Usually, you use this pattern when you are passing parameters into the method and need to validate them before actually performing the rest of the method.
但是,此代码无效,并且将无法编译:
This code, however, is not valid and will not compile:
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
的结果,而不要使用匿名类型,并从您的方法中返回该类的列表:
Following our conversation in the comments, you should probably create a class to hold the results of the Select
instead of using an anonymous type, and return a list of that class from your method:
// 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...
}
这篇关于如何将此代码转换为服务模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!