问题
I have a Project "Project.EntityFramework" which contains a context to my db. When attempting to consume the context from a separate project within the same solution "Project.Business" like:
using (var db = new EntityFramework.Entities())
{
// Code
}
I get the compiler error on "using":
Error 12 'EntityFramework.Entities': type used in a using statement must be implicitly convertible to 'System.IDisposable' ....
Now I can F12 and drill down to the Entities, and see it is implementing IDisposable - I can make this error go away if I put reference dlls to entity framework in "Project.Business" but this is defeating the purpose of what I wanted to accomplish - not having any dependency on EF within my Business layer.
Am I doing something wrong? Or is this just how it has to be?
回答1:
You're not doing anything wrong. If you want the business layer to not depend on EF, you'll need to wrap access to your DbContext class with something else. The Repository pattern is a popular one.
回答2:
To expand on @Spivonious' answer, here is what I did to accomplish the repository pattern on my DbContext - hopefully it's mostly implemented properly :/
public interface IFooEntity : IDisposable
{
IEnumerable<Foo> Get();
}
public class FooRepository : IFooEntity
{
private readonly Entities _context;
public FooService()
{
this._context = new Entities();
}
public IEnumerable<Foo> Get()
{
return _context.Foo;
}
public void Dispose()
{
_context.Dispose();
}
}
original code from question:
using (var db = new EntityFramework.Entities())
{
// Code
}
changed to:
using (var db = new EntityFramework.Repository.FooRepository())
{
// Code
}
this allowed my code in the separate project to use my repository rather than the context itself, allowing the business project to not have to rely on entity framework references.
回答3:
I had this same issue after adding some code and referencing a DLL with the model in it. After some head scratching I realised I hadn't referenced EntityFramework. The problem went away after adding that.
来源:https://stackoverflow.com/questions/25208243/entity-framework-5-library-consumers-need-entity-framework-dlls