具体的なリポジトリ用にサブクラス化される汎用リポジトリクラスとインタフェースを作成しました。継承が正常に動作しないAsp.netコア汎用リポジトリパターン
ジェネリックIRepositoryインターフェースとリポジトリクラス:
public interface IRepository<T> where T : BaseEntity
{
IEnumerable<T> GetAll();
T Get(long id);
void Insert(T entity);
void Update(T entity);
void Delete(T entity);
}
public class Repostitory<T> : IRepository<T> where T : BaseEntity
{
protected readonly ApplicationDbContext _context;
private DbSet<T> _entities;
private string errorMessage = string.Empty;
public Repostitory(ApplicationDbContext context)
{
this._context = context;
_entities = context.Set<T>();
}
public IEnumerable<T> GetAll()
{
return _entities.AsEnumerable();
}
public T Get(long id)
{
return _entities.SingleOrDefault(s => s.Id == id);
}
public void Insert(T entity)
{
CheckEntityNotNull(entity);
_entities.Add(entity);
_context.SaveChanges();
}
public void Update(T entity)
{
CheckEntityNotNull(entity);
_context.SaveChanges();
}
public void Delete(T entity)
{
CheckEntityNotNull(entity);
_entities.Remove(entity);
_context.SaveChanges();
}
private void CheckEntityNotNull(T entity)
{
if(entity == null)
{
throw new ArgumentNullException("Entity");
}
}
}
継承インターフェイスとクラス:
public interface IEventsRepository : IRepository<Event>
{
}
public class EventsRepository : Repostitory<Event>
{
public EventsRepository(ApplicationDbContext context) : base(context)
{
}
}
この時点では何の実装はまだありません。ここ
は、私のコードの一部でありますIEventsRepository
とEventsRepository
にありますが、一度これが動作するようになります。
ConfigureServices
方法
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddScoped(typeof(IRepository<>), typeof(Repostitory<>));
services.AddScoped(typeof(IEventsRepository), typeof(EventsRepository));
}
とコントローラで、これを持ってStartup.cs
で
:
public class AdminController : Controller
{
private readonly IEventsRepository _eventsRepository;
public AdminController(IEventsRepository eventsRepository)
{
_eventsRepository = eventsRepository;
}
[HttpGet]
public IActionResult EventsIndex()
{
var model = _eventsRepository.GetAll();
return View(model);
}
}
アプリケーションを構築するとき、私はすべてのエラーを取得しない、または私はホームページを開いた場合でも、 。
私は内部サーバーエラーが発生したEventsIndex
ページ開く:
InvalidCastException: Unable to cast object of type 'WebsiteProject.Repositories.EventsRepository`1[WebsiteProject.Models.Event]' to type 'WebsiteProject.Repositories.IEventsRepository`1[WebsiteProject.Models.Event]'.
が、私はここで何をしないのですか?
ジェネリックを作成するジェネリックを作成するときにジェネリックを作成するときには、まずこのようにテストする必要があります。例: 'Repository _event = new Repository ()';その中のメソッドを引き抜こうとしますか?それが動作するのを見ますか? –
Valkyrie
ジェネリック/ベースリポジトリの使用をやめてください。 – Phill
@Phill私はかなり長い間これを行う正しい方法を探してきました。これに近づくのが正しい方法を教えてください。 –