这个linq查询(DBContext)有什么问题? [英] What's wrong with this linq query (DBContext)?

查看:210
本文介绍了这个linq查询(DBContext)有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用VS2012和DBContext(实体框架)。



以下查询引发异常



客户托管;

  
使用(var context = new MiniNorthwindContext()){
cust =(从C中的c在context.Customers
其中c.CustomerName.Contains(SN)
select c) .SingleOrDefault();
}

当我运行它时会引发以下错误:序列包含多于一个元素。



如果我将其替换为

  ; 
使用(var context = new MiniNorthwindContext()){
cust =(from c in context.Customers
where c.CustomerName ==SN Software
select c)的SingleOrDefault();
}

然后它通过


解决方案

SingleOrDefault 可以执行以下三种操作之一:




  • 如果没有结果,返回默认值;

  • 如果有一个结果;返回它;

  • 如果有多个结果,则会抛出该异常。



所以您的查询匹配多行。


I'm using VS2012, and the DBContext (Entity Framework).

The following query throws an exception

Customer cust;
using (var context = new MiniNorthwindContext()) {
    cust = (from c in context.Customers
            where c.CustomerName.Contains("SN")
            select c).SingleOrDefault();
}

When I run it, it throws the following error: "Sequence contains more than one element".

If I replace it with

Customer cust;
using (var context = new MiniNorthwindContext()) {
    cust = (from c in context.Customers
            where c.CustomerName == "SN Software"
            select c).SingleOrDefault();
}

Then it passes.

What could I be doing wrong.

解决方案

SingleOrDefault can do one of three things:

  • if there are no results, return the default;
  • if there is one result; return it;
  • if there is more than one result, it throws that exception.

So your query is matching more than one row.

这篇关于这个linq查询(DBContext)有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆