英文:
Return multiple results from SQL Server
问题
public List<Product> GetProductByName(string name)
{
List<Product> productList = new List<Product>();
using (var context = _dbContextFactory.CreateDbContext())
{
productList = context.Product.Where(x => x.ProductName == name).ToList();
return productList;
}
}
英文:
Currently I can input a product name into a textbox and search that name in the SQL Server database. And return ONLY a single unique row. This works fine. But when I search for e.g. Bike. I need Blue bike AND Red Bike to be returned.
I currently have:
public List<Product> GetProductByName(string name)
{
List <Product> productList = new List<Product>();
using (var context = _dbContextFactory.CreateDbContext())
{
productList.Add(context.Product.SingleOrDefault(x => x.ProductName == name));
return productList;
}
}
Currently I'm getting a System.InvalidOperationException: 'Sequence contains more than one element'.
答案1
得分: 3
不要在期望有多行结果的情况下使用 SingleOrDefault
。也许可以考虑以下方式:
using (var context = _dbContextFactory.CreateDbContext())
{
return context.Product.Where(x => x.ProductName == name).ToList();
}
英文:
Don't use SingleOrDefault
if you're expecting multiple rows. Perhaps instead:
using (var context = _dbContextFactory.CreateDbContext())
{
return context.Product.Where(x => x.ProductName == name).ToList();
}
答案2
得分: 3
你可以在 Where 中使用 Contains:
using (var context = _dbContextFactory.CreateDbContext())
{
return context.Product.Where(x => x.ProductName.Contains(name)).ToList();
}
英文:
you can use Contains in Where:
using (var context = _dbContextFactory.CreateDbContext())
{
return context.Product.Where(x => x.ProductName.Contains(name)).ToList();
}
答案3
得分: 1
public List<Product> GetProductByName(string name)
{
List<Product> productList = new List<Product>();
using (var context = _dbContextFactory.CreateDbContext())
{
productList = context.Product.Where(x => x.ProductName == name).ToList();
return productList;
}
}
英文:
public List<Product> GetProductByName(string name)
{
List<Product> productList = new List<Product>();
using (var context = _dbContextFactory.CreateDbContext())
{
productList = context.Product.Where(x => x.ProductName == name).ToList();
return productList;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论