我有这个加入:
var mycust= db.CUSTOMER.Where(x => x.NAME.Contains(nameid)).ToList();
var CancCustomer = (from cust in myCust
join ip in db.IPS on must.ID equals ip.CUSTOMER_ID
select new JoinObj {ID = cust.ID, NAME = cust.NAME, LASTNAME = cust.LASTNAME,
TYPE_ID = ip.TYPE_ID, TYPE2_ID = ip.TYPE2_ID,
SERVICE_ID = ip.SERVICE_ID , REASON = ip.REASON }).ToList();
此代码多次返回第一个linq结果?我错过了什么?感谢。
答案 0 :(得分:2)
而不是Where
,您应该使用SingleOrDefault
/ Single
- 这些确实会在您的mycust
变量中返回一行。
SingleOrDefault
会将null
放入变量中(并假设Customer
是引用类型 - 如果它是值类型,则它将是类型的默认值)。如果没有找到任何项目或找到多个项目,Single
将抛出异常,这对于查找数据中的错误(例如重复的客户记录)非常有用。
此外,您的ip
表可能会为客户提供多个匹配记录 - 这就是为什么您会看到从select
返回多个记录的原因。
答案 1 :(得分:0)
您收到多个重复记录然后尝试以下quires
var mycust= db.CUSTOMER.Where(x => x.NAME.Contains(nameid)).ToList(); var CancCustomer = (from cust in myCust join ip in db.IPS on cust.ID equals ip.CUSTOMER_ID select new JoinObj {ID = cust.ID, NAME = cust.NAME, ASTNAME=cust.LASTNAME, TYPE_ID = ip.TYPE_ID, TYPE2_ID = ip.TYPE2_ID, SERVICE_ID = ip.SERVICE_ID , REASON = ip.REASON }).distinct().ToList();
其他明智的多条记录,然后您在查询后获得一条记录
var mycust= db.CUSTOMER.Where(x => x.NAME.Contains(nameid)).ToList(); var CancCustomer = (from cust in myCust join ip in db.IPS on must.ID equals ip.CUSTOMER_ID select new JoinObj {ID = cust.ID, NAME = cust.NAME, LASTNAME = cust.LASTNAME, TYPE_ID = ip.TYPE_ID, TYPE2_ID = ip.TYPE2_ID, SERVICE_ID = ip.SERVICE_ID , REASON = ip.REASON }).distinct().FirstOrDefault();