Sti*_*ian 1 c# linq entity-framework-core
我有这个动作方法,检查一个项目是否存在,如果存在,它将被删除.如果它不存在,则添加它.这就像是特定项目的开关:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> FrontPageProduct(ViewModelFrontPageProduct frontPageProduct)
{
var fpp = new FrontPageProduct()
{
ProductCategoryId = frontPageProduct.ProductCategoryId,
ProductId = frontPageProduct.ProductId,
SortOrder = 0
};
bool exists = _context.FrontPageProducts
.Any(x => x.ProductCategoryId == frontPageProduct.ProductCategoryId
&& x.ProductId == frontPageProduct.ProductId);
if (exists)
{
var delete = (from d in _context.FrontPageProducts
where (d.ProductCategoryId == frontPageProduct.ProductCategoryId &&
d.ProductId == frontPageProduct.ProductId)
select d).FirstOrDefault();
_context.Remove(delete);
}
else
{
_context.Add(fpp);
}
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index), new { id = fpp.ProductCategoryId, tab = 2 });
}
Run Code Online (Sandbox Code Playgroud)
现在,我觉得这有点长啰嗦.这样做是否有更短但仍然可读的方式?
您不必使用Any它来确定它是否存在.基本上加载它FirstOrDefault(我使用异步,因为我看到你在保存中使用异步,你也可以使用它FirstOrDefault).如果找到您有一个实例,您可以删除它而无需额外加载:
var fpp = new FrontPageProduct()
{
ProductCategoryId = frontPageProduct.ProductCategoryId,
ProductId = frontPageProduct.ProductId,
SortOrder = 0
};
var fppDB = await _context.FrontPageProducts
.FirstOrDefaultAsync(x => x.ProductCategoryId == frontPageProduct.ProductCategoryId && x.ProductId == frontPageProduct.ProductId);
if (fppDB != null)
{
_context.Remove(fppDB);
}
else
{
_context.Add(fpp);
}
await _context.SaveChangesAsync();
Run Code Online (Sandbox Code Playgroud)
否则,您也可以使用SQL存储过程并从EF调用此存储过程.它会更有效率.
| 归档时间: |
|
| 查看次数: |
105 次 |
| 最近记录: |