2

如果我有一个直接与我的数据库一起使用的模型(个人使用 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();
        }
    }
 }

VS

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

    public songs() {}
 }

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

4

2 回答 2

2

您不应该从域类访问数据。

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

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

使用存储库时,第二种方法是最好的。

示例布局:

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();
        } 
 }
}
于 2013-11-06T16:38:04.967 回答
0

如果您只想获得 1 首歌曲怎么办?我确定您不想加载所有歌曲。

如果我可以补充,你应该看看现有的项目或教程,看看如何做。请注意,我说can,您将阅读的绝不是这样做的方法。例如,@JeroenVannevel 推荐存储库模式,但有很多人反对它(使用 EF 时)。

我建议在决定您的数据访问策略之前浏览

于 2013-11-06T16:42:36.500 回答