0

I am utilizing ASP.NET WebAPI 2 & EF6 for a very small project which utilizes AutoFac to inject my DbContext directly into my controllers. I am not using a repository pattern as per Ryan's answer here: NOT using repository pattern, use the ORM as is (EF). To perform the injection, I went ahead and created an interface like so:

public interface IMoveGroupEntities : IDisposable
{
    System.Data.Entity.DbSet<HostEntry> HostEntries { get; set; }
    DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;
    Task<int> SaveChangesAsync();
}

Then implemented the interface on a partial class which sits in conjunction with my generated entities like so:

public partial class MoveGroupEntities : IMoveGroupEntities
{
}

I have a sneaking suspicion I'm doing something incorrectly here as I feel like this line:

DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;

Shouldn't be needed, but it does appear to be necessary as "Entry" is used from within my scaffolded API controller.

Can anyone chime in here on a better way to achieve this?

Community
  • 1
  • 1
cjones26
  • 3,459
  • 1
  • 34
  • 51

1 Answers1

1

The best you can say about scaffolded code is: it works. It's not the best code architecturally. I fully agree with the link you quote, but that doesn't mean that the controllers should be in touch with EF artifacts directly (including Entry).

I think it's a mistake to replace one DbSet wrapper (repository) by another wrapper. The gist of the answer is: use the context (and DbSets, etc.) directly in your code. That is: don't use wrappers. That is not: use contexts (etc.) anywhere. You're doing the exact opposite: you create a different type of wrapper in order to use EF anywhere. But it's a good thing that your gut feeling doesn't really like it.

I always prefer to keep action methods (MVC, Web API) small. Basically, I just make them call a service method. It's the service that deals with contexts and everything EF has to offer. These services may be in a separate assembly, but wherever they are, they are injected into the controllers by dependency injection and, likewise, they obtain their contexts by DI.

Community
  • 1
  • 1
Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
  • Thanks Gert--could you elaborate on the differences between repository and service patterns? Do simply expose business logic from your service as opposed to simple CRUD operations? – cjones26 Oct 19 '15 at 20:12
  • 1
    For the really simple CRUD operations scaffolding code is sufficient and convenient (although so far I never used it, we use Breeze for simple data access). When it gets a little bit more complex (i.e. implementing a business use case) I always use service methods that I can test in integration test and that can also be used by other applications in the same suite. – Gert Arnold Oct 19 '15 at 20:16