我的C#MVC项目设置看起来如何?
|
我是C#和MVC的新手。我已经读了几本书,并花了很多时间在这个网站上阅读有关各种主题的问答。我启动并运行了一个测试项目,以获取查询组列表并将其返回到简单视图的基础知识。我喜欢Repository模式的想法,并在实现它方面有所作为。一些注意事项...目前,我不使用EF或Linq2Sql,但也许将来使用。我不确定是将我的using语句保留在GroupRepository中还是通过Try / Catch / Finally添加一些Dispose语句,因为我仍然需要一种方法来管理异常。
当我继续学习时,只想对我当前的设置提供一些建议/评论。
Base.cs
namespace Test.Models
{
public class Base : IDisposable
{
protected string Connection
{
get
{
return System.Configuration.ConfigurationManager.ConnectionStrings[\"TestDB\"].ConnectionString;
}
}
}
}
Group.cs
namespace Test.Models
{
public class Group
{
public int ID { get; set; }
public string Name { get; set; }
public bool IsActive { get; set; }
public DateTime Created { get; set; }
}
}
GroupRepository.cs
namespace Test.Models
{
public class GroupRepository : Base, IGroupRepository
{
public List<Group> GetAllGroups()
{
List<Group> groups = new List<Group>();
SqlDataReader reader;
using (SqlConnection conn = new SqlConnection(Connection))
using (SqlCommand cmd = new SqlCommand(\"GetAllGroups\", conn))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
conn.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
Group group = new Group();
group.ID = reader.GetInt32(0);
group.Name = reader.GetString(1);
group.IsActive = reader.GetBoolean(2);
group.Created = reader.GetDateTime(3);
groups.Add(group);
}
}
return groups;
}
}
}
IGroupRepository.cs
namespace Test.Models
{
public interface IGroupRepository
{
List<Group> GetAllGroups();
}
}
组控制器
namespace Test.Controllers
{
public class GroupController : Controller
{
private IGroupRepository _repository;
public GroupController() : this(new GroupRepository())
{
}
public GroupController(IGroupRepository repository)
{
_repository = repository;
}
public ActionResult Index()
{
return View(_repository.GetAllGroups());
}
}
}
视图
@model IEnumerable<Test.Models.Group>
@{
ViewBag.Title = \"Group List\";
}
<table>
@foreach (var item in Model) {
<tr>
<td>
@item.ID
</td>
<td>
@item.Name
</td>
<td>
@item.IsActive
</td>
<td>
@item.Created
</td>
</tr>
}
</table>
谢谢大家!
没有找到相关结果
已邀请:
1 个回复
埠仙俊
这样,您只有一个方法“ GetGroups”,就可以随意更改查询参数和基础逻辑,而不必每次想添加新的接口时都重新定义接口查询。