简体   繁体   English

使用DbContext在Oracle会话开始时运行sql查询

[英]Run sql query at the beginning of an Oracle session using DbContext

The requirement is to execute a sql query using DbContext (EF 5 in DatabaseFirst mode) at the beginning of every Oracle session that DbContext might invoke. 要求是在DbContext可能调用的每个Oracle会话的开始时,使用DbContext(在DatabaseFirst模式下为EF 5)执行sql查询。
Putting this in the constructor gives inconsistent results because there are instances where this sql query is not run at all when expected. 将其放在构造函数中会产生不一致的结果,因为在某些情况下,此sql查询根本不会在预期的情况下运行。

The setup is EF5 in DBFirst mode connecting to Oracle10gR2 using ODP.NET v12 Managed driver. 该设置为DBFirst模式下的EF5,使用ODP.NET v12托管驱动程序连接到Oracle10gR2。

public partial class MyContext : DbContext
{
    public MyContext(string connectionString)
        : base(connectionString)
    {
        Database.ExecuteSqlCommand(Constants.SqlQuery);
    }
}

I instantiate the context by passing the connecting string because the connection string needs to be dynamic as follows: 我通过传递连接字符串来实例化上下文,因为连接字符串需要如下动态:

using(var context = new MyContext(GetConnectionString()))
{
  ...
  ...
  context.SaveChanges();
}

Is there a way to ensure that this query is always run whenever an Oracle session is created? 有没有一种方法可以确保在创建Oracle会话时始终运行此查询?

You can extend the DbContext class and implement each method to do so. 您可以扩展DbContext类并实现每种方法。 For example.... 例如....

public KashDbContext : DbContext
{
    public int SaveChanges()
    {
        Database.ExecuteSqlCommand(Constants.SqlQuery);
        base.SaveChanges();
    }

    //Do for all methods
}

Just implement the OnContextCreated() method in your partial class: 只需在您的局部类中实现OnContextCreated()方法即可:

    partial void OnContextCreated()
    {
        this.ExecuteStoreCommand(Constants.SqlQuery, new object[] { });
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM