Asp.net mvc &引用;“适当的”;MVC-我是否应该使用构造函数?

Asp.net mvc &引用;“适当的”;MVC-我是否应该使用构造函数?,asp.net-mvc,entity-framework,entity-framework-4,entity-framework-5,entity-framework-6,Asp.net Mvc,Entity Framework,Entity Framework 4,Entity Framework 5,Entity Framework 6,如果我有一个直接与数据库一起工作的模型(个人使用ASP.NET w\Entity Framework),我应该使用构造函数来设置变量吗 例如: public class songs { public IEnumerable<songs> allSongs {get; } public songs() { using (var context = new entities()) { allSongs =

如果我有一个直接与数据库一起工作的模型(个人使用ASP.NET w\Entity Framework),我应该使用构造函数来设置变量吗

例如:

public class songs
{
    public IEnumerable<songs> allSongs {get; }

    public songs()
    {
        using (var context = new entities())
        {
            allSongs = context.songs.orderBy(n => n.name).toList();
        }
    }
 }
公共类歌曲
{
公共IEnumerable所有歌曲{get;}
公共歌曲()
{
使用(var context=new entities())
{
allSongs=context.songs.orderBy(n=>n.name.toList();
}
}
}
VS

公共类歌曲
{
公共数字所有歌曲
{
得到
{
使用(var context=new entities())
{
allSongs=context.songs.orderBy(n=>n.name.toList();
}
}
}
公共歌曲(){}
}

从技术上讲,两者都是正确的,但哪个更正确?我唯一能想到的只有一个正确答案的地方是,我正在设置的变量是否需要在操作期间始终更新或保持不变。

您不应该从域类访问数据

您应该创建一个与数据库交互的
SongRepository
。您向控制器注入此存储库,当您想要歌曲列表时,只需引用该存储库即可

歌曲
实际上应该是它自己的实体时,这可能会变得有点棘手。但是,我强烈建议您实现存储库模式

第二种方法在使用存储库时效果最好

布局示例:

public class SongController : Controller {
 private SongRepository _songRepository;

 public SongController(SongRepository repo) {
  _songRepository = repo;
 }

 public ActionResult ShowSongs(){
  return View(_songRepository.GetAllSongs());
 }
}

public class SongRepository {
 public IEnumerable<Song> GetAllSongs(){
  using (var context = new entities())
        {
            allSongs = context.songs.orderBy(n => n.name).toList();
        } 
 }
}
公共类控制器:控制器{
私有歌曲库(SongRepository);;
公共SongController(SongRepo存储库){
_songRepository=回购;
}
公共行动结果ShowSongs(){
返回视图(_songRepository.GetAllSongs());
}
}
公共类存储库{
公共IEnumerable GetAllSongs(){
使用(var context=new entities())
{
allSongs=context.songs.orderBy(n=>n.name.toList();
} 
}
}

如果你只想要一首歌怎么办?我肯定你不想加载所有的歌曲

如果我可以补充的话,你应该看看现有的项目,或者看看如何做。请注意,我说的可以,您将阅读的内容绝不是做这件事的方法。例如,@jeroenvanevel建议使用repository模式,但有很多人反对(在使用EF时)


我建议在决定您的数据访问策略之前,先浏览中的首要问题。

我不确定您对域类的理解。你能提供一个参考来帮助我理解为什么我的例子不属于最佳实践吗?以上只是一个例子。我真的想在每次需要处理数据时创建一个存储库吗。正如@Stijn在下面所说的,我不会总是获取数据库中每个项目的副本。@DR913:您应该使用
ninject
之类的工具注入存储库,这样可以确保只有一个存储库可以在任何地方使用。我将在讲座结束后3-4小时内详细阐述我的答案(如果那时还没有人这么做的话)
public class SongController : Controller {
 private SongRepository _songRepository;

 public SongController(SongRepository repo) {
  _songRepository = repo;
 }

 public ActionResult ShowSongs(){
  return View(_songRepository.GetAllSongs());
 }
}

public class SongRepository {
 public IEnumerable<Song> GetAllSongs(){
  using (var context = new entities())
        {
            allSongs = context.songs.orderBy(n => n.name).toList();
        } 
 }
}