How do you execute native SQL using Entity Framework when using the DataContext through an Interface

 ̄綄美尐妖づ 提交于 2019-12-12 03:03:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!