Last active
October 2, 2024 13:45
-
-
Save mrpmorris/fca0e31b50a9bb760ffe5aab8893a507 to your computer and use it in GitHub Desktop.
Internal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.EntityFrameworkCore; | |
public abstract class EntityBase<TKey> where TKey : IEquatable<TKey> | |
{ | |
public abstract TKey Id { get; set; } | |
} | |
public abstract class RepositoryBase<TDbContext, TEntity, TKey> | |
where TDbContext : DbContext, new() | |
where TEntity : EntityBase<TKey> | |
where TKey : IEquatable<TKey> | |
{ | |
public async ValueTask<TEntity?> GetAsync(TKey id) | |
{ | |
var dbContext = new TDbContext(); | |
IQueryable<TEntity> queryable = GetQueryable(dbContext!)!; | |
TEntity? result = await queryable.FirstOrDefaultAsync(x => Equals(x.Id, id)); | |
return result; | |
} | |
protected abstract IQueryable<TEntity> GetQueryable(TDbContext context); | |
} | |
internal class ApplicationDbContext : DbContext | |
{ | |
} | |
public class User : EntityBase<Guid> | |
{ | |
public override Guid Id { get; set; } = Guid.NewGuid(); | |
} | |
// The consuming app doesn't need ApplicationDbContext, just User and UserRepository, | |
// so why can't I declare the class of this type? | |
// and why can't I override a protected method considering the class is sealed so | |
// a consuming app cannot override it? | |
public sealed class UserRepository : RepositoryBase<ApplicationDbContext, User, Guid> | |
{ | |
protected override IQueryable<User> GetQueryable(ApplicationDbContext context) | |
{ | |
throw new NotImplementedException(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment