C
C#17mo ago
1grumpydev

❔ How to handle null in Interface

I'm trying to learn .Net Core MVC and I'm following a course where the following code gives a warning of a possible null reference return. Can some one tell me how to best handle this? public async Task<T> GetByIdAsync(int id) { var result = await _context.Set<T>().FirstOrDefaultAsync(n => n.Id == id); return result; }
18 Replies
Thinker
Thinker17mo ago
Return Task<T?> instead
Angius
Angius17mo ago
(and don't use generic repositories on top of EF, for all that is holy, do not)
1grumpydev
1grumpydev17mo ago
I'm not quite following you regarding "Return Task<T?>.
Thinker
Thinker17mo ago
Change the return type from Task<T> to Task<T?>
1grumpydev
1grumpydev17mo ago
Geez, I feel stupid. Thanks! Also regarding the other comment, so it is a bad practice to use a generic repository as it is being used?
Thinker
Thinker17mo ago
(read up on nullable reference types if you want more information about what the ? does)
Angius
Angius17mo ago
EF's DbContext already implements Unit of Work, and each DbSet is already a repository Wrapping a repository in a repository makes about as much sense as
public static class MyConsole
{
public static void WriteLine(string line)
{
Console.WriteLine(line);
}
}
public static class MyConsole
{
public static void WriteLine(string line)
{
Console.WriteLine(line);
}
}
Denis
Denis17mo ago
Generic repository is a redundant abstraction. I've tried implementing it, based on a Udemy course. Didn't see a real benefit
Angius
Angius17mo ago
If the course demands it, sure, proceed with the course
Denis
Denis17mo ago
Only made my code more complicated
Angius
Angius17mo ago
But it's a lot of code that just does nothing
1grumpydev
1grumpydev17mo ago
Ah, I see yeah in this Udemy course the instructor was trying to demonstrate separate of concern by doing it like this instead of just handling it in the controller Thanks for the explanation
Monsieur Wholesome
But what if you want to move away from the EF dependency Kappa
Angius
Angius17mo ago
Then you'll have to rewrite a lot of code anyway ¯\_(ツ)_/¯
Monsieur Wholesome
Not if you apply your on repo pattern
Klarth
Klarth17mo ago
Then all you need to do is rewrite all of your queries from Linq to SQL. Really minor change. kappa
Monsieur Wholesome
At least it would all be in the very few classes of your repositories, centralized to the very few intended places, and not scattered all over your 21287 thousand file project Kappa
Accord
Accord17mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.