【问题标题】:How to convert my sql query to linq query如何将我的 sql 查询转换为 linq 查询
【发布时间】:2022-01-20 12:50:39
【问题描述】:

嗨,我写了这个 sql 查询,但我想写 linq 版本 sql版本

Select CalisanId From Calisanlar Where Lisans=0 INTERSECT (Select CalisanId From Covids) 
  

        public List<LisansCovid> GetLisansCovid()
            {
                using (SirketDBContext context = new SirketDBContext())
                {
                    var result =
        (from cal1 in context.Calisanlar
         where cal1.Lisans == 0
         select cal1.CalisanId)
        .Intersect
            (from cal2 in context.Covids
             select cal2.CalisanId);
    
     //exception              return result.ToList();        
            }}

【问题讨论】:

  • 这能回答你的问题吗? Linq to SQL and Intersect
  • 没有。对不起:(
  • 为什么不呢?是等价的函数。
  • 到目前为止你做了什么?你能给我们看看吗?
  • 我不是代码编写工厂。 Stack Overflow 可帮助诊断和解决问题;帮助学习。

标签: mysql sql linq tsql linq-to-sql


【解决方案1】:

尝试以下,未测试;假设数据库连接db:

var infoQuery =
    (from cal1 in db.Calisanlar
    where cal1.Lisans == 0
    select cal1.CalisanId)
    .Intersect
        (from cal2 in db.Covids
        select cal2.CalisanId);
var result = inforQuery?.ToList() ?? 0;

或者,lambda表达式

var infoQuery = 
    (db.Calisanlar.Where(x => x.Lisans == 0).Select(x => x.CalisanId))
    .Instersect(db.Covids.Select(x => x.CalisanId))

更新 假设CalisanID 是integer 检查null 返回,如果找到则返回零。同样,未经测试。

【讨论】:

  • 首先谢谢,但是当我写 return infoQuery.ToList(); 时我没有工作。我编辑了我的代码。你可以看到
  • 答案已更新以允许返回 null。但是,仍然需要样本数据来了解查询返回 null 的原因。
猜你喜欢
  • 2020-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-08
  • 2014-08-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多