底层连接已关闭连接意外关闭

时间:2014-05-08 09:53:50

标签: entity-framework asp.net-mvc-4

在使用以下查询

时使用实体框架时遇到问题

控制器

TestPlanService.TestPlanServiceClient svclient = new TestPlanService.TestPlanServiceClient();

            try
            {
                return svclient.GetTestPlans().ToList();
            }
            catch (Exception ex)
            {
                string exmess = ex.InnerException.Message;
            }

查询

    using (DataModelContainer db = new DataModelContainer())
                {
                    db.Configuration.LazyLoadingEnabled = false;
                    db.Configuration.ProxyCreationEnabled = false;

                    var query = (from c in db.TestPlans.Include(x => x.TestPoints)
                                 select c);
                    var result = query.ToList();
                    return result;
})

在上面的代码中虽然我能够从db中返回列表并且加载了所有子元素

模型如下

public partial class TestPlan
    {
        public TestPlan()
        {
            this.TestPoints = new HashSet<TestPoint>();
        }

        public int TestPlanId { get; set; }
        public string TestPlanName { get; set; }
        public int TestPlanTypeId { get; set; }
        public int RiskTierID { get; set; }

        public virtual ICollection<TestPoint> TestPoints { get; set; }
        public virtual TestPlanType TestPlanType { get; set; }
        public virtual RiskTierMaster RiskTierMaster { get; set; }
    }

public partial class TestPoint
    {
        public TestPoint()
        {
            this.TestPlans = new HashSet<TestPlan>();
        }

        public int TestPointId { get; set; }
        public string TestPointName { get; set; }
        public int TestMethodId { get; set; }
        public Nullable<int> PassThreshold { get; set; }
        public Nullable<int> FailThreshold { get; set; }
        public int OrganizationID { get; set; }
        public string CreatedBy { get; set; }

        public virtual TestMethod TestMethod { get; set; }
        public virtual ICollection<TestPlan> TestPlans { get; set; }
        public virtual OrganizationMaster OrganizationMaster { get; set; }
    }

测试计划可以有多个测试点。 我能够从服务返回结果但不幸的是在控制器端它抛出错误 &#34;底层连接已关闭:连接意外关闭&#34;

如果有人对此有任何解决方案,请告诉我。

1 个答案:

答案 0 :(得分:0)

@Aron,

你说得对,我想这是因为序列化错误。 对于正在寻找这个问题的其他人来说,这就是帮助我的原因。

在我生成.tt文件的实体模型.edmx文件中,只需添加两行代码,如下所示。应该对该模型中的所有实体进行此操作

我已将它应用于我的一个班级,如下所示,

using System.Runtime.Serialization;    
[DataContract(IsReference = true)]
public partial class TestPlanType
{
    public TestPlanType()
    {
        this.TestPlans = new HashSet<TestPlan>();
    }

    public int TestPlanTypeId { get; set; }
    public string TestPlanTypeName { get; set; }

    public virtual ICollection<TestPlan> TestPlans { get; set; }
}

this article helped me