Sql server 使用Linq向上和向下移动记录到SQL
我需要实现一个函数,用于上下移动记录(排序)并使用Linq to SQL保存排序器。我使用的是SQL Server2000,但如果有一个新版本的SQL Server解决方案,我可能可以升级。我很想听听您对如何操作的想法。只需在表中添加一个整数列Sql server 使用Linq向上和向下移动记录到SQL,sql-server,linq-to-sql,Sql Server,Linq To Sql,我需要实现一个函数,用于上下移动记录(排序)并使用Linq to SQL保存排序器。我使用的是SQL Server2000,但如果有一个新版本的SQL Server解决方案,我可能可以升级。我很想听听您对如何操作的想法。只需在表中添加一个整数列索引,并根据用户输入修改此索引-上移只是减少所选记录的索引值,增加前面记录的索引值 public void MoveUp(Guid id) { Item item = Context.Items.Single(i => i.Id == id)
索引
,并根据用户输入修改此索引-上移只是减少所选记录的索引值,增加前面记录的索引值
public void MoveUp(Guid id)
{
Item item = Context.Items.Single(i => i.Id == id);
if (item.Index > 0)
{
Item predecessor = Context.Items.Single(i => i.Index == item.Index - 1);
item.Index -= 1;
predecessor.Index += 1;
Context.SaveChanges();
}
}
向下移动时,做相反的操作,您就完成了。如果您对多个表需要此功能,只需使用界面创建一个通用版本。谢谢Daniel!
通过查看您的示例,我提出了在一个类别中对产品进行排序的方法
public void MoveUp(int categoryId, int productId, int originalIndex, int newIndex)
{
if (newIndex == originalIndex) return;
var product = _context.CategoryProducts.Single(x => x.CategoryId == categoryId && x.ProductId == productId);
product.SortOrder = newIndex;
_context.CategoryProducts
.Where(x =>
x.CategoryId == categoryId &&
x.ProductId != productId &&
x.SortOrder >= newIndex &&
x.SortOrder <= originalIndex)
.Update(x => { x.SortOrder = x.SortOrder + 1; });
_context.SubmitChanges();
}
public void MoveDown(int categoryId, int productId, int originalIndex, int newIndex)
{
if (newIndex == originalIndex) return;
var product = _context.CategoryProducts.Single(x => x.CategoryId == categoryId && x.ProductId == productId);
product.SortOrder = newIndex;
_context.CategoryProducts
.Where(x =>
x.CategoryId == categoryId &&
x.ProductId != productId &&
x.SortOrder >= originalIndex &&
x.SortOrder <= newIndex)
.Update(x => { x.SortOrder = x.SortOrder - 1; });
_context.SubmitChanges();
}
public-void-MoveUp(int-categoryId、int-productId、int-originalIndex、int-newIndex)
{
if(newIndex==originalIndex)返回;
var product=\u context.CategoryProducts.Single(x=>x.CategoryId==CategoryId&&x.ProductId==ProductId);
product.SortOrder=newIndex;
_context.CategoryProducts
.其中(x=>
x、 类别ID==类别ID&&
x、 ProductId!=ProductId&&
x、 排序器>=新索引&&
x、 SortOrder{x.SortOrder=x.SortOrder+1;});
_context.SubmitChanges();
}
公共void向下移动(int categoryId、int productId、int originalIndex、int newIndex)
{
if(newIndex==originalIndex)返回;
var product=\u context.CategoryProducts.Single(x=>x.CategoryId==CategoryId&&x.ProductId==ProductId);
product.SortOrder=newIndex;
_context.CategoryProducts
.其中(x=>
x、 类别ID==类别ID&&
x、 ProductId!=ProductId&&
x、 排序器>=原始索引&&
x、 SortOrder{x.SortOrder=x.SortOrder-1;});
_context.SubmitChanges();
}
我使用来自的UpdateExtension进行实际更新