今日已更新 264 条资讯 | 累计 23847 条内容
关于我们

标签:#efcore

找到 1 篇相关文章

AI 资讯

EF Core Is Already a Repository. Stop Wrapping It in Another One.

Open a lot of .NET projects and you'll find the repository pattern sitting on top of Entity Framework Core. IProductRepository, GetById, Add, Save, the whole set. Underneath, every method just calls the EF Core DbContext and passes the result straight back. The wrapper adds a name and nothing else. So do you need the repository pattern with EF Core? For most apps, no. EF Core already gives you one. DbSet is a repository. It already does the thing the pattern is for. The reason this keeps happening is that the repository pattern got taught alongside EF, so people assume you need one to use the other. You don't. What the Pattern Was For The repository pattern came before EF Core. It started in a time when data access meant hand-written SQL, SqlCommand, and mapping DataReader rows to objects by hand. Wrapping all of that behind an interface was worth it. It hid a real mess, and it let you swap what was underneath without the rest of the app noticing. EF Core already does that. DbContext is the unit of work. DbSet is the repository. SaveChanges() is the commit. The pattern you're adding is one the tool already gives you. What the Wrapper Actually Does Here's the shape you see in most codebases: public class ProductRepository : IProductRepository { private readonly AppDbContext _db ; public ProductRepository ( AppDbContext db ) => _db = db ; public async Task < Product ?> GetById ( int id ) => await _db . Products . FindAsync ( id ); public async Task < List < Product >> GetAll () => await _db . Products . ToListAsync (); public void Add ( Product product ) => _db . Products . Add ( product ); } Read what each method does. GetById calls FindAsync. GetAll calls ToListAsync. Add calls Add. It's a passthrough. Every line hands the call straight to EF Core and returns whatever comes back. You wrote an interface, a class, and a registration to rename methods that already existed. This is what people mean by a generic repository over EF Core, and it's the most common version y

2026-07-22 原文 →