C
C#2y 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
Thinker2y ago
Return Task<T?> instead
Angius
Angius2y ago
(and don't use generic repositories on top of EF, for all that is holy, do not)
1grumpydev
1grumpydevOP2y ago
I'm not quite following you regarding "Return Task<T?>.
Thinker
Thinker2y ago
Change the return type from Task<T> to Task<T?>
1grumpydev
1grumpydevOP2y 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
Thinker2y ago
(read up on nullable reference types if you want more information about what the ? does)
Angius
Angius2y 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
Denis2y ago
Generic repository is a redundant abstraction. I've tried implementing it, based on a Udemy course. Didn't see a real benefit
Angius
Angius2y ago
If the course demands it, sure, proceed with the course
Denis
Denis2y ago
Only made my code more complicated
Angius
Angius2y ago
But it's a lot of code that just does nothing
1grumpydev
1grumpydevOP2y 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
Angius2y ago
Then you'll have to rewrite a lot of code anyway ¯\_(ツ)_/¯
Monsieur Wholesome
Not if you apply your on repo pattern
Klarth
Klarth2y 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
Accord2y 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.
Want results from more Discord servers?
Add your server