C
C#•11mo ago
DevDream

Generic Method Type Parameter to create DbSet for my Database query?

I want to make my code reusable by passing a type parameter to a generic method and using that parameter to create a Dbset for my Database Query. The method I want to pass it to is GetUnPagedList(). I'm using .NET Core 7 for this project. Thank you for reading.
7 Replies
Jimmacle
Jimmacle•11mo ago
where exactly are you stuck? use the Set<T> method on your context to get a dbset with a generic type
Angius
Angius•11mo ago
Does every model have a relationship to ApplicationUser? And, similarly, CreationDate? If not, you would have to start by declaring those in an interface And constraining the generic to that interface Or, what I like to do, use an extension method on IQueryable<IThatInterface> instead
DevDream
DevDreamOP•11mo ago
@🅱immacle Im stuck on GetUnPagedList method and converting it to a Generic Method to even pass the Entity @ZZZZZZZZZZZZZZZZZZZZZZZZZ Yes let me post my DB Context and Model one moment Database Context File Post Model Identity User Model
Angius
Angius•11mo ago
Seems like only Post has .ApplicationUser property
DevDream
DevDreamOP•11mo ago
@ZZZZZZZZZZZZZZZZZZZZZZZZZ Yeah only 2 of my DB models have a relationship with Application User
Angius
Angius•11mo ago
So, I'd start with an interface Then, constrain your method's generic
private IEnumerable <T> GetUnpagedList<T>() where T : IWhatever
private IEnumerable <T> GetUnpagedList<T>() where T : IWhatever
Then use context.Set<T>() to get the DbContext of a given type
DevDream
DevDreamOP•11mo ago
Thank You! You guys are awesome for the lightning fast replies I owe you one Solved by @ZZZZZZZZZZZZZZZZZZZZZZZZZ
Want results from more Discord servers?
Add your server