❔ 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
Return
Task<T?>
instead(and don't use generic repositories on top of EF, for all that is holy, do not)
I'm not quite following you regarding "Return Task<T?>.
Change the return type from
Task<T>
to Task<T?>
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?
(read up on nullable reference types if you want more information about what the
?
does)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
Generic repository is a redundant abstraction. I've tried implementing it, based on a Udemy course. Didn't see a real benefit
If the course demands it, sure, proceed with the course
Only made my code more complicated
But it's a lot of code that just does nothing
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
But what if you want to move away from the EF dependency
Then you'll have to rewrite a lot of code anyway ¯\_(ツ)_/¯
Not if you apply your on repo pattern
Then all you need to do is rewrite all of your queries from Linq to SQL. Really minor change.
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
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.