[英]Better understanding of Entity Framework Core querying and DbSet impact
[英]Is there a better way to generalize dbSet with the same attribute - Entity Framework
我有一個共同的模式
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)
}
創建一個接受Func
作為參數的方法可能是您正在尋找的。
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;
});
我嘗試了許多不同的方法(使用dynamic
或 DbSet< T>),但並不認為我只對 ID 進行過濾,所以這就是為什么我可以只傳遞List<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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.