【发布时间】:2021-01-14 09:21:49
【问题描述】:
我已经按照Adam Freeman 的书学习了 ASP.NET MVC 5。我已经实现了书中描述的存储库模式。我正在使用 WHERE 并使用 SQL-EventProfiler 记录 SQL 命令,然后我将看不到 WHERE 条件。
这是我的示例代码,用于我使用 Ninject 的存储库:
public interface IHelpRepository {
IEnumerable<Help> Helps { get; }
}
public class HelpRepository : IHelpRepository {
private HelpDBContext context = new HelpDBContext();
public IEnumerable<Help> Helps {
get { return context.Helps; }
}
}
public class Help {
[Required]
[Key]
public int Id { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Description { get; set; }
}
public class HelpController : Controller {
private IHelpRepository HelpRepository;
public HelpController (IHelpRepository helpRepository) {
this.HelpRepository= helpRepository;
}
public ActionResult HelpDescription(int Id) {
Help help = helpRepository.Helps.Where(h => h.Id == Id).SingleOrDefault<Help>();
return View("HelpDescription", help);
}
}
生成的 SQL 命令 (XEventProfiler):
SELECT [Extent1].[Id] AS [Id], [Extent1].[Title] AS [Title], [Extent1].[Description] AS [Description] FROM [dbo].[Helps] AS [Extent1 ]
为什么生成的 SQL 命令中不包含 WHERE?
【问题讨论】:
-
在 EF 等更高级别的 ORM 之上使用时,通用存储库实际上是一种反模式。你的问题是后果之一。 DbContetx 不是连接或数据库模型,它是控制多个实体的工作单元。 DbSet已经是一个存储库。通过转换为
IEnumerable,您实际上是在执行查询并将所有内容加载到内存中 -
现在,您的存储库类只是委托给 DbSet 类,同时阻止您组合实体。这种贫乏的存储库类没有任何好处,只有问题。检查No need for repositories and unit of work with Entity Framework Core 看看有什么问题
标签: asp.net asp.net-mvc linq entity-framework-6 repository-pattern