返回来自SQL Server的多个结果

huangapple go评论54阅读模式
英文:

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&lt;Product&gt; GetProductByName(string name)
{
    List &lt;Product&gt; productList = new List&lt;Product&gt;();
    using (var context = _dbContextFactory.CreateDbContext())
    {
        productList.Add(context.Product.SingleOrDefault(x =&gt; 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 =&gt; 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 =&gt; 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&lt;Product&gt; GetProductByName(string name)
{
    List&lt;Product&gt; productList = new List&lt;Product&gt;();
    using (var context = _dbContextFactory.CreateDbContext())
    {
        productList = context.Product.Where(x =&gt; x.ProductName == name).ToList();
        return productList;
    }
}

huangapple
  • 本文由 发表于 2023年2月6日 19:39:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/75360838.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定