问题
SETUP
Ok so I have an application that follows the Onion archetecture approach i.e:
Frontend References > Services and Domain
Service References > Domain and Data
Data References > Domain
Domain References > nothing
I am using the latest version of EF and I am also using Unity as my IOC.
PROBLEM
The service layer of my application accesses the DataContext in the Data layer via an Interface.
public class TestService : ITestService
{
private readonly IDataContext _context;
public TestService(IDataContext context)
{
_context = context;
}
public BaseResponse SomeServiceCall(BaseRequest request)
{
_context.Database.ExecuteSqlCommand("SELECT * FROM test");
}
}
public class DataContext : DbContext, IDataContext
{
public DataContext() :
base("DefaultConnection")
{
Database.SetInitializer<DataContext>(null);
}
public DataContext(string connection) :
base(connection)
{
Database.SetInitializer<DataContext>(null);
}
public Database Database { get; set; }
Public IDBContext<Test> Tests {get;set;}
}
public interface IDataContext
{
Database Database { get; set; }
IDBContext<Test> Tests {get;set;}
}
I had to expose the Database object in order to get acess to the ExecuteSQL method. But now when I run this in my service, The database object returns a null reference exception and I do not know how to initialize it. Any help would be greatly appreciated!
Josh
回答1:
You don't initialize Database
object. It is initialized automatically by the context - if your code uses a real context. Btw. you don't need to expose database. You can expose a method on your context interface and wrap the database access in its implementation on your derived context.
来源:https://stackoverflow.com/questions/15441398/how-do-you-execute-native-sql-using-entity-framework-when-using-the-datacontext