存储过程失去连接

发布于 2024-10-01 17:16:52 字数 5574 浏览 0 评论 0原文

我有一个 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();

当我尝试将列表分配给 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
}

I have an ASP.NET MVC project in which the model is managed through .NET entities and it seems that some times it loses the connection, but this happens only on stored procedures.

I get the following error:

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

Why is this happening?

Code

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


var catss = GetCategoriesStructure().ToList();

this exception occurs when I am trying to assign the List to catss variable

Object Context Instantiation

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
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

躲猫猫 2024-10-08 17:16:52

在不知道如何实例化 ObjectContext 的情况下,我将在此处将一些内容扔到答案桶中。

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

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

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

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

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

Without knowing how you are instantiating your ObjectContext, I'll throw something in the answer bucket here.

This is how I do my Entity Framework commands and connections (for small simple projects at least):

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

You can also optionally pass in a connection string when instantiating your context (if not, it will use the one in your app.config):

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

If this does not help your issue, please help us understand your code a little better by posting how you are creating your ObjectContext. You could at least attempt to do it this way to see if it works; that will tell you whether it is an issue with your connection string or not.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文