GetStoredProcCommand的Enterprise Library 6.0数据访问问题

时间:2015-04-22 06:49:50

标签: enterprise-library enterprise-library-6

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

<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();
        }
    }
}

但我们收到错误“ExecuteNonQuery:Connection属性尚未初始化。” at cmd.ExecuteNonQuery() 如果我们用db.ExecuteNonQuery(cmd)替换cmd.ExecuteNonQuery(),那么它可以工作。

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

1 个答案:

答案 0 :(得分:0)

至少,请检查一下,以便知道您的数据库已初始化。

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
        {
        } 
    }

}

每次通话我都会得到一个“新鲜”的数据库。使用后,让它超出范围并收集垃圾。