C# Linq 2 Sql-除非在控制器内完成查询,否则存储库不会工作
我真的很难理解我面临的问题。我有一个非常简单的存储库,其中包含以下代码:C# Linq 2 Sql-除非在控制器内完成查询,否则存储库不会工作,c#,.net,linq-to-sql,orm,C#,.net,Linq To Sql,Orm,我真的很难理解我面临的问题。我有一个非常简单的存储库,其中包含以下代码: public class ProductRepository : IProductRepository { private Table<Product> productTable; public Product GetProductById(int id) { return productTable.Where(p => p.ProductId == id).S
public class ProductRepository : IProductRepository
{
private Table<Product> productTable;
public Product GetProductById(int id)
{
return productTable.Where(p => p.ProductId == id).Single();
}
public IQueryable<Product> GetProducts()
{
return productTable;
}
}
我想问题可能是我需要在我要返回的班级中使用IQueryable。我还以各种方式修改了AddToCart方法,以使其正常工作
public IQueryable<Product> GetProductById(int id)
{
return productTable.Where(p => p.ProductId == id);
}
public void AddToCart(int productId)
{
//Throws error / Returns Null value
Product product = productRepository.GetProductById(productId).Single();
//Returns Null value
Product product = productRepository.GetProductById(productId).FirstOrDefault();
}
如果没有更多的信息,很难看出问题出在哪里 GetProductById如何返回null?Single不允许返回null,如果没有返回项或返回多个项,则将抛出InvalidOperationException。 GetProducts有什么不同之处?看看你的代码,应该没有任何问题。 当你尝试这个时会发生什么
public class ProductRepository : IProductRepository
{
private Table<Product> productTable;
public Product GetProductById(int id) {
return GetProducts().Where(p => p.ProductId == id).Single();
}
public IQueryable<Product> GetProducts() {
return productTable;
}
}
作为补充说明,如果您确定集合中只存在一项,则应避免使用Single。单曲将永远贯穿你的整个系列。第一种方法在这方面效率更高。我想知道您的依赖注入是否有问题。您正在使用.Single,根据文档,如果集合中没有一个项目满足您的条件,它将抛出异常
我会尝试在不使用依赖注入的情况下实现它,看看是否能得到相同的结果。您还可以尝试直接从GetProductById方法实例化并返回产品项,而不是从数据库中提取,以排除DI中发生的任何奇怪情况 如何/何时在ProductRepository中创建productTable?productRepository的实例是如何创建的?@contactmatt,您使用的是什么DI/IOC框架?我相信您的问题主要与此相关,即在一个用例中,框架正确地注入了productTable,而在另一个用例中,它不是!你的桌子被Ninject注射了吗?如果是这样的话,我们能看到绑定吗?我在这里的评论与我在你的另一个问题上的评论相同:如果你设置context.Log=Console.Out;它是否为每个查询显示相同的SQL?@Gabe,我检查一下。我目前不在VisualStudio中测试它,但是context.Log写在哪里?到visual studio控制台?无法获取产品。Singlep=>p.ProductId==id;更直截了当一点?重要的是我们要找出问题所在。我的方法实际上是一个创可贴解决方案,应该告诉我们,这种方法是否比我们所看到的要多。
public void AddToCart(int productId)
{
Product product = productRepository.GetProducts().FirstOrDefault(p => p.ProductId == productId);
}
public class ProductRepository : IProductRepository
{
private Table<Product> productTable;
public Product GetProductById(int id) {
return GetProducts().Where(p => p.ProductId == id).Single();
}
public IQueryable<Product> GetProducts() {
return productTable;
}
}