存储过程失去连接

时间:2010-11-10 10:58:16

标签: c# .net entity-framework stored-procedures ado.net

我有一个ASP.NET MVC项目,其中模型通过.NET实体进行管理,有时它似乎失去了连接,但这只发生在存储过程上。

我收到以下错误:

Execution of the command requires an open and available connection. The connection's current state is broken.

为什么会这样?

代码

public ObjectResult<Categories> GetCategoriesStructure() {
        return ObjectContext.getCategoriesStructure();
    }


var catss = GetCategoriesStructure().ToList();

当我尝试将List分配给catss变量

时,会发生此异常

对象上下文实例化

public abstract class ObjectContextManager {
    /// <summary>
    /// Returns a reference to an ObjectContext instance.
    /// </summary>
    public abstract TObjectContext GetObjectContext<TObjectContext>()
        where TObjectContext : ObjectContext, new();
}

 public abstract class BaseDAO<TObjectContext, TEntity> : IBaseDAO<TObjectContext, TEntity>
    where TObjectContext : System.Data.Objects.ObjectContext, new()
    where TEntity : System.Data.Objects.DataClasses.EntityObject {

    private ObjectContextManager _objectContextManager;

    /// <summary>
    /// Returns the current ObjectContextManager instance. Encapsulated the 
    /// _objectContextManager field to show it as an association on the class diagram.
    /// </summary>
    private ObjectContextManager ObjectContextManager {
        get { return _objectContextManager; }
        set { _objectContextManager = value; }
    }

    /// <summary>
    /// Returns an ObjectContext object. 
    /// </summary>
    protected internal TObjectContext ObjectContext {
        get {
            if (ObjectContextManager == null)
                this.InstantiateObjectContextManager();

            return ObjectContextManager.GetObjectContext<TObjectContext>();
        }
    }

    /// <summary>
    /// Default constructor.
    /// </summary>
    public BaseDAO() { }

    /// <summary>
    /// Instantiates a new ObjectContextManager based on application configuration settings.
    /// </summary>
    private void InstantiateObjectContextManager() {
        /* Retrieve ObjectContextManager configuration settings: */
        Hashtable ocManagerConfiguration = ConfigurationManager.GetSection("ObjectContextManagement.ObjectContext") as Hashtable;
        if (ocManagerConfiguration != null && ocManagerConfiguration.ContainsKey("managerType")) {
            string managerTypeName = ocManagerConfiguration["managerType"] as string;
            if (string.IsNullOrEmpty(managerTypeName))
                throw new ConfigurationErrorsException("The managerType attribute is empty.");
            else
                managerTypeName = managerTypeName.Trim().ToLower();

            try {
                /* Try to create a type based on it's name: */
                Assembly frameworkAssembly = Assembly.GetAssembly(typeof(ObjectContextManager));
                Type managerType = frameworkAssembly.GetType(managerTypeName, true, true);

                /* Try to create a new instance of the specified ObjectContextManager type: */
                this.ObjectContextManager = Activator.CreateInstance(managerType) as ObjectContextManager;
            } catch (Exception e) {
                throw new ConfigurationErrorsException("The managerType specified in the configuration is not valid.", e);
            }
        } else
            throw new ConfigurationErrorsException("ObjectContext tag or its managerType attribute is missing in the configuration.");
    }

    /// <summary>
    /// Persists all changes to the underlying datastore.
    /// </summary>
    public void SaveAllObjectChanges() {
        this.ObjectContext.SaveChanges();
    }

    /// <summary>
    /// Adds a new entity object to the context.
    /// </summary>
    /// <param name="newObject">A new object.</param>
    public virtual void Add(TEntity newObject) {
        this.ObjectContext.AddObject(newObject.GetType().Name, newObject);
    }
    /// <summary>
    /// Deletes an entity object. 
    /// </summary>
    /// <param name="obsoleteObject">An obsolete object.</param>
    public virtual void Delete(TEntity obsoleteObject) {
        this.ObjectContext.DeleteObject(obsoleteObject);
    }

    public void Detach(TEntity obsoleteObject) {
        this.ObjectContext.Detach(obsoleteObject);
    }

    /// <summary>
    /// Updates the changed entity object to the context.
    /// </summary>
    /// <param name="newObject">A new object.</param>
    public virtual void Update(TEntity newObject) {
        ObjectContext.ApplyPropertyChanges(newObject.GetType().Name, newObject);
        ObjectContext.Refresh(RefreshMode.ClientWins, newObject);
    }

    public virtual TEntity LoadByKey(String propertyName, Object keyValue) {
        IEnumerable<KeyValuePair<string, object>> entityKeyValues =
           new KeyValuePair<string, object>[] {
       new KeyValuePair<string, object>(propertyName, keyValue) };

        // Create the  key for a specific SalesOrderHeader object. 
        EntityKey key = new EntityKey(this.ObjectContext.GetType().Name + "." + typeof(TEntity).Name, entityKeyValues);
        return (TEntity)this.ObjectContext.GetObjectByKey(key);
    }

    #region IBaseDAO<TObjectContext,TEntity> Members


    public bool validation(TEntity newObject) {
        return newObject.GetType().Name.ToString() == "Int32";
    }

    #endregion
}

1 个答案:

答案 0 :(得分:2)

在不知道你如何实例化你的ObjectContext的情况下,我会在答案桶中添加一些内容。

这就是我执行Entity Framework命令和连接的方式(至少对于小型简单项目):

using (MyEntities context = new MyEntities())
{
    return context.getCategoriesStructure();
}

您还可以选择在实例化上下文时传入连接字符串(如果没有,它将使用app.config中的连接字符串):

new MyEntities("...connection string...")

如果这对您的问题没有帮助,请通过发布您ObjectContext的创建方式,帮助我们更好地了解您的代码。你至少可以尝试这样做,看它是否有效;这会告诉你它是否是你的连接字符串的问题。