Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 存储过程失去连接_C#_.net_Entity Framework_Stored Procedures_Ado.net - Fatal编程技术网

C# 存储过程失去连接

C# 存储过程失去连接,c#,.net,entity-framework,stored-procedures,ado.net,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 GetCategoriesStructure(){ 返回ObjectCo

我有一个ASP.NET MVC项目,在该项目中,模型通过.NET实体进行管理,似乎有时会丢失连接,但这种情况仅发生在存储过程上

我得到以下错误:

Execution of the command requires an open and available connection. The connection's current state is broken.
为什么会这样

代码

public ObjectResult GetCategoriesStructure(){
返回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
}
公共抽象类ObjectContextManager{
/// 
///返回对ObjectContext实例的引用。
/// 
公共抽象TObjectContext GetObjectContext()
其中TObjectContext:ObjectContext,new();
}
公共抽象类BaseDAO:ibaseado
其中TObjectContext:System.Data.Objects.ObjectContext,new()
其中tenty:System.Data.Objects.DataClasses.EntityObject{
私有ObjectContextManager_ObjectContextManager;
/// 
///返回当前ObjectContextManager实例
///_objectContextManager字段,将其显示为类图上的关联。
/// 
专用ObjectContextManager ObjectContextManager{
获取{return}objectContextManager;}
设置{u objectContextManager=value;}
}
/// 
///返回ObjectContext对象。
/// 
受保护的内部TObjectContext对象上下文{
得到{
如果(ObjectContextManager==null)
此参数为.instanceObjectContextManager();
返回ObjectContextManager.GetObjectContext();
}
}
/// 
///默认构造函数。
/// 
公共BaseDAO(){}
/// 
///根据应用程序配置设置实例化新的ObjectContextManager。
/// 
私有void实例化对象上下文管理器(){
/*检索ObjectContextManager配置设置:*/
Hashtable ocManagerConfiguration=ConfigurationManager.GetSection(“ObjectContextManagement.ObjectContext”)作为Hashtable;
if(ocManagerConfiguration!=null&&ocManagerConfiguration.ContainsKey(“managerType”)){
字符串managerTypeName=ocManagerConfiguration[“managerType”]作为字符串;
if(string.IsNullOrEmpty(managerTypeName))
抛出新的ConfigurationErrorsException(“managerType属性为空”);
其他的
managerTypeName=managerTypeName.Trim().ToLower();
试一试{
/*尝试基于其名称创建类型:*/
Assembly frameworkAssembly=Assembly.GetAssembly(typeof(ObjectContextManager));
类型managerType=frameworkAssembly.GetType(managerTypeName,true,true);
/*尝试创建指定ObjectContextManager类型的新实例:*/
this.ObjectContextManager=Activator.CreateInstance(managerType)作为ObjectContextManager;
}捕获(例外e){
抛出新的ConfigurationErrorsException(“配置中指定的managerType无效。”,e);
}
}否则
抛出新的ConfigurationErrorsException(“配置中缺少ObjectContext标记或其managerType属性”);
}
/// 
///保留对基础数据存储的所有更改。
/// 
public void SaveAllObjectChanges(){
this.ObjectContext.SaveChanges();
}
/// 
///将新实体对象添加到上下文中。
/// 
///一个新的物体。
公共虚拟空添加(TEntity newObject){
this.ObjectContext.AddObject(newObject.GetType().Name,newObject);
}
/// 
///删除实体对象。
/// 
///过时的东西。
公共虚拟无效删除(TEntity obsoleteObject){
this.ObjectContext.DeleteObject(obsoleteObject);
}
公共无效分离(潜在废弃对象){
this.ObjectContext.Detach(废弃对象);
}
/// 
///将更改的实体对象更新到上下文。
/// 
///一个新的物体。
公共虚拟无效更新(TEntity newObject){
ObjectContext.ApplyPropertyChanges(newObject.GetType().Name,newObject);
Refresh(RefreshMode.ClientWins,newObject);
}
公共虚拟TEntity LoadByKey(字符串propertyName、对象keyValue){
IEnumerable entityKeyValues=
新的KeyValuePair[]{
新的KeyValuePair(propertyName,keyValue)};
//为特定SalesOrderHeader对象创建密钥。
EntityKey=new EntityKey(this.ObjectContext.GetType().Name+“”+typeof(tenty.Name,entityKeyValues);
返回(tenty)this.ObjectContext.GetObjectByKey(key);
}
#区域委员会成员
公共布尔验证(TEntity newObject){
返回newObject.GetType().Name.ToString()=“Int32”;
}
#端区
}

在不知道如何实例化
ObjectContext
的情况下,我将在这里的答案桶中抛出一些东西

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

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


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

请告诉我,您没有试图为所有查询打开一个连接。我忘了提到最重要的连接。无论是mvc还是web表单,重要的是项目是否使用.net实体开发。所以,我想我已经回答了你的问题。谢谢你的回复,你是说“通过实体框架管理”吗
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
}
using (MyEntities context = new MyEntities())
{
    return context.getCategoriesStructure();
}
new MyEntities("...connection string...")