gpt4 book ai didi

c# - 如果它存在,.Remove()它,如果不存在,.Add()它

转载 作者:太空宇宙 更新时间:2023-11-03 19:43:59 25 4
gpt4 key购买 nike

我有这个操作方法来检查项目是否存在,如果存在,则将其删除。如果不存在,则将其添加。它就像那个特定项目的开关:

[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 });
}

现在,我觉得这有点啰嗦。是否有更短但仍可读的方式来执行此操作?

最佳答案

您不必使用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();

否则,您也可以使用 SQL 存储过程并从 EF 调用此过程。效率会更高。

关于c# - 如果它存在,.Remove()它,如果不存在,.Add()它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48702535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com