【问题标题】:SQL command into linq expression entity frameworkSQL命令进入linq表达式实体框架
【发布时间】:2017-12-19 18:13:25
【问题描述】:

我有 2 张桌子:Oceny_przedmioty 和 Studenci。 Studenci 和 Oceny_przedmioty 是一对多的连接(一个学生可以有超过 1 个等级)。我需要从这个 SQL 中生成:

SELECT Oprz_Ocena 
    FROM Oceny_przedmioty 
    UNION SELECT ST_Nr_indeksu 
          FROM Studenci 
          WHERE ST_Nr_indeksu = '11000'

Visual Studio 能理解的linq 表达式。我使用实体框架。 我试过这样的东西

   var currentGrade= (from Oceny_przedmioty in dbContext.Oceny_przedmioty
                            select Oceny_przedmioty.ID_Studenta).Union
                             (from Studenci in dbContext.Studenci
                              select Studenci.ID_Studenta);

但它甚至不识别 Union(不包含 Union 的定义)。提前感谢您的帮助!

【问题讨论】:

  • 您的代码 sn-p 看起来不错。确保您有 using System.Linq; 以便使用 .Union() 函数
  • 这对你有用吗??
  • 嗨!我正在使用 System.Linq,我有这个问题:“'IQueryable' 不包含 'Union 的定义和最佳扩展方法重载 'ParallelEnumerable.Union(ParallelQuery, IEnumerable)' 需要类型为“ParallelQuery”的接收器。
  • 看起来 Oceny_przedmioty.ID_Studenta 类型是 int?(可为空的 int),而 Studenci.ID_Studenta 只是 intUnion 的部分必须具有相同的元素类型。为什么不选择与您的 SQL 查询对应的字段(似乎是strings)。
  • select Oceny_przedmioty.ID_Studenta.Value替换select Oceny_przedmioty.ID_Studenta

标签: c# sql-server visual-studio entity-framework linq


【解决方案1】:

你可以这样试试。包括命名空间using System.Linq;(如果尚未完成)

var india = context.Orders.Where(o => o.ShipCountry == "India").Select(o => o);
var usa= context.Orders.Where(o => o.ShipCountry == "USA").Select(o => o);
var IndiaUnionusa = india.Union(usa);

你的代码就像

 var quer1= (from Oceny_przedmioty in dbContext.Oceny_przedmioty
                            select Oceny_przedmioty.ID_Studenta);
 var query2 = (from Studenci in dbContext.Studenci
                              select Studenci.ID_Studenta);
  var currentGrade = query1.Union(query2);

int 似乎有问题?可空类型

 var quer1= (from Oceny_przedmioty in dbContext.Oceny_przedmioty
                            select Oceny_przedmioty.ID_Studenta)
                            .ToList();
 var query2 = (from Studenci in dbContext.Studenci
                              select Studenci.ID_Studenta)
                             .ToList();
 var currentGrade = query1.Union(query2);

【讨论】:

  • 感谢您的回复!不幸的是,Union 行在哪里我有这个错误:“IQueryable' 不包含'Union 的定义和最佳扩展方法重载'ParallelEnumerable.Union(ParallelQuery, IEnumerable) ' 需要类型为 'ParallelQuery" 的接收器
  • @AleksandraSkoczypiec - 更新了我的答案,你现在可以试试吗
【解决方案2】:

感谢大家的回复!问题也出在查询上,这段代码解决了我所有的问题

var query1 = dbContext.Oceny_przedmioty    
           .Join(dbContext.Studenci,
              post => post.ID_Studenta,        
              meta => meta.ID_Studenta,  
              (post, meta) => new { meta.ST_Nr_indeksu, post.OPrz_Ocena })
            .Where(postAndMeta => postAndMeta.ST_Nr_indeksu == 11000);    

       dataGridView1.DataSource = query1.ToList();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-07
    • 1970-01-01
    • 1970-01-01
    • 2017-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多