我有一個共同的模式
bool doesLinkExist = await [DBSet]
.AnyAsync(model => model.PartId == parameters.PartId).ConfigureAwait(false);
if(doesLinkExist)
throw exception (which has different messages)
[DBSet]=>資料庫中的表。
如果我創建一個方法,它真的很容易傳遞例外訊息,但資料庫集似乎是問題,因為代碼不知道不同 [DBset] s/表中有 PartId 列
繞過這個問題并創建通用方法的方法是什么?
編輯:在 2 個詞中,我想將 [DBSet] 作為引數傳遞
這是我希望這種方法看起來像的方式
private Task CheckLinkExistAsync(int idForLookUp, string errorMsg, DBSet table, CancellationToken cancellationToken)
{
bool LinkExist = await table.AnyAsync(model => model.Id == idForLookUp, cancellationToken).ConfigureAwait(false);
if(LinkExist)
throw exception (which has different messages)
}
uj5u.com熱心網友回復:
創建一個接受 aFunc作為引數的方法可能是您正在尋找的。
private async Task<IActionResult> CheckLinkExistsAsync(int id, string errorMessage, Func<Task<T>> func)
{
bool exists = await _modelRepository.Any(x => x.Id == id);
if (exists)
{
return await func();
}
throw new Exception(errorMessage);
}
之后就可以這樣消費了
await CheckLinkExistsAsync(1, "Custom Error Message", async () => {
// DO STUFF AND RETURN
var t = new T();
return t;
});
uj5u.com熱心網友回復:
我嘗試了許多不同的方法(使用dynamic或 DbSet< T>),但不認為我只對 ID 進行過濾,所以這就是為什么我可以通過 aList<int>并對其進行過濾
private void CheckLinkExistsAsync(int partId, string errorMessage, List<int> idsToLookup)
{
bool exists = idsToLookup.Any(id => id == partId);
if(exists)
throw new Exception(errorMessage);
}
我這樣稱呼它
CheckLinkExistsAsync(parameters.PartId, "ExceptionMessage",
await Db.Table.Select(model => model.PartId).ToListAsync(cancellationToken).ConfigureAwait(false));
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/346740.html
