Enterprise Library 6.0 Data Access issue with GetStoredProcC



我正在尝试使用Enterprise Library 6.0数据块构建数据访问层。 下面是我的配置文件

<configuration>  
  <configSections>
    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true"/>
  </configSections>
  <dataConfiguration defaultDatabase="db"/>
  <connectionStrings>
      <add name="db" connectionString="..." providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

下面是我的班级文件

public class MasterRepo
{
    Database db = null;
    static MasterRepo()
    {
        DatabaseFactory.SetDatabaseProviderFactory(new DatabaseProviderFactory());
    }
    public MasterRepo()
    {
        db = DatabaseFactory.CreateDatabase("db");
    }
    public int Save(int param1, int param2)
    {
        using (DbCommand cmd = db.GetStoredProcCommand("Save", param1, param2))
        {
            return cmd.ExecuteNonQuery();
        }
    }
}

但是如果我们将cmd.ExecuteNonQuery()替换为db,则在cmd.ExecuteNonQuery()上收到错误"ExecuteNonQuery:连接属性尚未初始化"。ExecuteNonQuery(cmd) 然后它就可以工作了。

那么为什么它首先失败了,处理这个问题的好方法是什么?

至少,进行检查,以便您知道数据库已初始化。

public int Save(int param1, int param2)
{
    if(null!=db)
    {
        using (DbCommand cmd = db.GetStoredProcCommand("Save", param1, param2))
        {
            return cmd.ExecuteNonQuery();
        }
    }
    else
    {
        throw new NullReferenceException("Database (db) was null.  This was not expected.");
    }
}

我通常这样做:

public abstract class DataLayerBase
{
    private string _instanceName = string.Empty;
    public DataLayerBase()
    {
    }
    public DataLayerBase(string instanceName)
    {
        this._instanceName = instanceName;
    }
    protected Database GetDatabase()
    {
        Database returnDb = null;
        if (this._instanceName.Length > 0)
        {
            returnDb = DatabaseFactory.CreateDatabase(this._instanceName);
        }
        else
        {
            returnDb = DatabaseFactory.CreateDatabase();
        }
        return returnDb;
    }
}

public class ZebraData : DataLayerBase
{
    //Procedures
    private readonly string PROC_ZEBRA_GET_ALL = "[dbo].[uspZebraGetAll]";
    public ZebraData() : base()
    {
    }
    public ZebraData(string instanceName) : base(instanceName)
    {
    }
    public IDataReader ZebraGetAll()
    {
        IDataReader idr = null;
        try
        {
            Database db = base.GetDatabase();
            DbCommand dbc = db.GetStoredProcCommand(this.PROC_ZEBRA_GET_ALL);
            idr = db.ExecuteReader (dbc);
            return idr;
        }
        finally
        {
        } 
    }

}

每次调用时,我都会得到一个"新鲜"数据库。 使用后,让它超出范围并收集垃圾。

相关内容

  • 没有找到相关文章

最新更新