We are using the repository pattern in our ASP.NET MVC 3 application. This means that, although we use EF 4.1 Code First to access the data in the backend, all MVC controllers do that via a generic repository class rather than directly over the DbContext subclass.
Simplified code snippet:
public class MyEntityContext : DbContext, IMyEntityContext
{
public IDbSet MyEntities { get; set; }
...
}
public class MyEntityRepository : IMyEntityRepository
{
private IMyEntityContext _context;
public IQueryable<MyEntity> MyEntities
{
return _context.MyEntities;
}
...
}
public class MyEntityController : Controller
{
private MyEntityRepository _repository;
...
}
We use interfaces and dependency injection for every dependency. It works fine. Looks nice, doesn't it? But now for the caveat:
We also provide a WCF Data Service (CTP supporting Code First) to access the entities. We want to use the repository in that service, too. But this seems tricky. When using the MyEntityContext
directly, the service looks like this:
public class MyEntityService : DataService<MyEntityContext>
{
public static void InitializeService(DataServiceConfiguration config)
{
config.SetEntitySetAccessRule("MyEntities", EntitySetRights.All);
}
}
But when I try to replace the MyEntityContext
by the repository, there are two issues:
- The type specified for the generic
DataService<..>
needs to be a class with a default constructor, which breaks the pretty design-by-contract and dependency injection design. - It even seems that the type provided has to be a
DbContext
class: I tried and used theMyEntityRepository
instead, but failed (see details).
I seem lost... Can anyone bring me back on the proper track?
Details:
My first go was:
public class MyEntityService : DataService<MyEntityRepository>
{
...
However, when calling the service, it fails with the following error message:
The server encountered an error processing the request. The exception message is 'On data context type 'MyEntityRepository', there is a top IQueryable property 'MyEntities' whose element type is not an entity type. Make sure that the IQueryable property is of entity type or specify the IgnoreProperties attribute on the data context type to ignore this property.'.
I tried the following steps to fix this, but did not get rid of this error message:
- Adding a
[DataServiceKey("MyEntityId")]
to MyEntity, where MyEntityId is the correct key property of the entity. - Replacing the type of
Repository.MyEntities
byIDbSet
instead ofIQueryable
.
BTW: The following posts are not duplicates:
- WCF Repository Service pattern with entity framework
- Service Layer/Repository Pattern
- Best way to implement Repository Pattern?
- webservices with repository pattern in c# and WCF?
- WCF Service design pattern