Mad*_*r24 4 c# sql linq entity-framework linq-to-sql
我需要运行一个LINQ查询,它将返回3行(当前记录,上一条记录,以及相对于当前记录的下一条记录.CroductID是我自动生成的标识列.
目前我正在使用Union LINQ语句执行此操作,但我不确定是否有更好或更有效的方法来完成相同的任务.
这是我得到的:
var ProductID = 10;
var Results = (from p in DB.Products
where p.ProductID == ProductID - 1 //Previous record.
select new Product
{
    ProductID = p.ProductID,
    ProductTitle = p.ProductTitle,
    Views = p.Views,
}).Union(from p in DB.Products
where p.ProductID == ProductID //Current record
select new Product
{
    ProductID = p.ProductID,
    ProductTitle = p.ProductTitle,
    Views = p.Views,
}).Union(from p in DB.Products
where p.ProductID == ProductID + 1 //Next record.
select new Product
{
    ProductID = p.ProductID,
    ProductTitle = p.ProductTitle,
    Views = p.Views,
});
这应该为ProductID 9,ProductID 10,ProductID 11返回3行.谢谢!
就个人而言,我会使用这种方法:它有利于在范围内缺少ID的地方工作.一个勇敢的人假设所有的ID都被计算和存在.
 var currAndNext = Context.Set<TPoco>()
                  .Where<TPoco>(t=>t.id == id)
                  .OrderBy(t=>t.id)
                  .Skip(0)
                  .Take(2);
 var prev = Context.Set<TPoco>()
                  .Where<TPoco>(t=>t.id == id)
                  .OrderByDescending(t=>t.id)
                  .Skip(1)
                  .Take(1);
您的方法可以像这样更简短地重写:
var ProductID = 10;
var Results = (from p in DB.Products
where p.ProductID >= ProductID - 1 &&
      p.ProductID <= ProductID + 1
select new Product
{
   ProductID = p.ProductID,
   ProductTitle = p.ProductTitle,
   Views = p.Views,
});
但请注意,仅当没有从 Products 表中删除与指定的 ProductID 对应的记录时,这才会返回您需要的内容。
| 归档时间: | 
 | 
| 查看次数: | 4222 次 | 
| 最近记录: |