0

我想用一个函数来用linq查询db并结合它们的结果,我写了如下代码但不能工作,任何人都可以帮助我吗?谢谢!

错误:(操作无法完成,因为 DbContext 已被释放)

部分代码:

public static IEnumerable<UserLocation> loadedUserList;

public static IEnumerable<UserLocation> combinedUserList;


public static void loadDataInStaticClass()
            {
                using (var context = new SptialTestEntities())
                {
                    var loadedUserList = from newRcords in context.UserLocations
                                         where newRcords.ID > lastLoadedID
                                         select newRcords;

                    if (loadedUserList.Any())
                    {
                        foreach (var user in loadedUserList)
                        {
                            Console.WriteLine(user.UserName);

                        }
                        if (combinedUserList != null)
                        {
                            combinedUserList = loadedUserList.Union(combinedUserList);
                            foreach (var cc in combinedUserList)
                            {
                                Console.WriteLine("\n after combined:" + cc.UserName);
                            }
                        }
                        else
                        {
                            combinedUserList = loadedUserList;
                            Console.WriteLine("\nfirst run :" + combinedUserList.Count());
                            foreach (var cc in combinedUserList)
                            {
                                Console.WriteLine("\n user:" + cc.UserName);
                            }

                        }
                    }

                }


            }

问题是:第一次调用没问题,第二次报错:操作无法完成,因为DbContext已经被释放了,怎么办?谢谢!

4

1 回答 1

0

我粘贴了整个代码,有人可以运行并检查错误并感谢您:userLocation 一个表包含用户 ID、用户名、用户位置(地理类型),并且我在 Visual Studio 2012 中使用用户数据库第一模式并将 userLocation 映射到一个实体空间测试实体。

Program.cs
static void Main(string[] args)
{

  for (int i = 1; i < 3; i++)
   {
      Console.WriteLine("\nrun{0}times, i);
      Test.LoadUsersFromDB();
   }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Data.Spatial;
using System.Data.Entity;
using System.Xml.Linq;
using System.IO;
using System.Configuration;
using System.Web;
using System.Web.Script.Serialization;
using System.Collections;
using System.Globalization;

namespace SptialMatch
{
    class Test
    {
        public static int lastedLoadedRecordID = 14;

        public static IEnumerable<UserLocation> loadedUserList;
        public static IEnumerable<UserLocation> combinedUserList;

        public static void LoadUsersFromDB()
        {
            try
            {
                Console.WriteLine("\n------------------------load data begin----------------------------------------------------------");

                //var context = new SptialTestEntities();
                using (var context = new SptialTestEntities())
                {
                    System.Diagnostics.Stopwatch loadStopwatch = new System.Diagnostics.Stopwatch();
                    loadStopwatch.Start();

                    loadedUserList = from newRcords in context.UserLocations
                                      where newRcords.ID > lastedLoadedRecordID
                                      select  newRcords;
                   if (loadedUserList.Any())
                    {
                        foreach (var loadUser in loadedUserList)
                        {
                            Console.WriteLine("\n loaded element:" + loadUser.UserName);
                        }
                        if (combinedUserList != null)
                        {
                            Console.WriteLine("\nnot first run:" );
                            foreach (var cc in combinedUserList)
                            {
                                Console.WriteLine("\n before union:" + cc.UserName);
                            }


                            IEnumerable<UserLocation> tmp = loadedUserList.AsEnumerable();
                            combinedUserList = tmp.Union<UserLocation>(combinedUserList.AsEnumerable(), new UserComparer2()).ToList();

                            Console.WriteLine("\nnot first run after union:" );
                            foreach (var cc in combinedUserList)
                            {
                                Console.WriteLine("\n after union the user name is:" + cc.UserName);
                            }

                        }
                        else
                        {
                            combinedUserList = loadedUserList;
                            Console.WriteLine("\nfirst run the count is:" + combinedUserList.Count());
                            foreach (var cc in combinedUserList)
                            {
                                Console.WriteLine("\n the combined list:" + cc.UserName);
                            }
                        }

                        var maxID = loadedUserList.Max(myMaxID => myMaxID.ID);

                        lastedLoadedRecordID = lastedLoadedRecordID + 1;

                    }
                    else
                    {
                        Console.WriteLine("\n no new data!");
                        Console.WriteLine("\n-----------------load end,no new data yet------------------------------------------------");

                        Thread.Sleep(3000);
                    }
                    loadStopwatch.Stop();
                    Console.WriteLine("\nload time cost{0} seconds。", loadStopwatch.Elapsed);
                    Console.WriteLine("\n---------------------load end ----------------------------------------------------------");

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("\n exception message:" + ex.Message);

            }




        }

    }


    class UserComparer2 : IEqualityComparer<UserLocation>
    {
        public bool Equals(UserLocation x, UserLocation y)
        {

            //Check whether the compared objects reference the same data.
            if (Object.ReferenceEquals(x, y)) return true;

            //Check whether any of the compared objects is null.
            if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
                return false;

            //Check whether the products' properties are equal.
            return x.ID == y.ID && x.UserName == y.UserName;
        }

        // If Equals() returns true for a pair of objects 
        // then GetHashCode() must return the same value for these objects.

        public int GetHashCode(UserLocation user)
        {
            //Check whether the object is null
            if (Object.ReferenceEquals(user, null)) return 0;

            //Get hash code for the Name field if it is not null.
            int hashUserName = user.UserName == null ? 0 : user.UserName.GetHashCode();

            //Get hash code for the Code field.
            int hashUserCode = user.ID.GetHashCode();

            //Calculate the hash code for the product.
            return hashUserName ^ hashUserCode;
        }

    }
}
于 2013-05-07T06:46:33.367 回答