【问题标题】:EF Core - FromSql throwing invalid number when parameterizing collection of numbersEF Core - FromSql 在参数化数字集合时抛出无效数字
【发布时间】:2020-09-01 20:47:36
【问题描述】:

我正在使用 Entity Framework Core 并尝试将整数集合转换为字符串,然后将字符串作为参数传递给 FromSql 函数。

这是我的问题的简化示例:

IQueryable<Equipment> query = _context.Set<Equipment>();

const string s = "150999, 720045, 720046";

IQueryable<SignalGantryEquipment> filteredSignalGantryEquipments 
                = query.FromSql("select id, name from equipment " +
                                "where id in ({0}) and type = {1} " + 
                                "order by name", s, equipmentId)
                    .Select(x => new Equipment
                    {
                        Id = x.Id,
                        Name = x.Name
                    });

return filteredSignalGantryEquipments;

我希望上面的代码可以工作。但是,我收到以下错误:

问题是 100% 与参数化字符串 s 相关,因为我已经测试了 equipmentId

我发现很奇怪的是,如果我删除字符串 s 作为参数并将值硬编码到位,它会按预期工作而没有错误。

IQueryable<SignalGantryEquipment> filteredSignalGantryEquipments 
                = query.FromSql("select id, name from signal_gantry_equipment " +
                                "where id in (150999, 720045, 720046) and equipment_type = {0} " + 
                                "order by name", equipmentId)
                    .Select(x => new SignalGantryEquipment
                    {
                        Id = x.Id,
                        Name = x.Name
                    });

为什么会这样,如何将整数集合作为参数?

【问题讨论】:

  • 你必须使用原始 SQL 吗?如果不是这样,使用 Linq 可以做得更干净(imo)。

标签: c# oracle entity-framework entity-framework-core grpc


【解决方案1】:

问题是形成的查询将如下所示。请注意,您尝试作为一组传递的内容实际上只是一个字符串,Oracle DB 提供程序在其中期望一组数字(我假设 ints)。

select id, name from equipment where id in ('150999, 720045, 720046')...

如果您不介意使用完整的 Linq,这里有一个选项:

var idList = new List<int>(){ 150999, 720045, 720046 };

// making some guesses on property names below
// also - is it correct to be comparing equipment type to variable named equipmentId?

return _context.Set<Equipment>()
   .Where(e => idList.Contains(e.Id) && e.EquipmentType == equipmentId)
   .ToList();

【讨论】:

  • 感谢您的帮助。这澄清了我的理解。对于我的情况,我正在使用的数据库有点混乱,所以我最初认为原始 sql 会更好地工作。我已经改用 LINQ,以你的为例,做了一些调整,效果很好。再次感谢。
  • 很高兴听到这个消息!如果我的解决方案对您有用,如果您接受答案,我将非常感激(答案左侧的复选标记)。在我个人看来,在原始 SQL 上使用 LINQ 的能力是 EF Core 的最大优势之一。它有一点学习曲线,但它是构建可查询对象的一种非常强大且(再次认为)干净的方式!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-01
  • 1970-01-01
  • 2014-02-23
  • 1970-01-01
  • 2019-02-26
  • 2019-01-25
  • 1970-01-01
相关资源
最近更新 更多