如何将多次函数调用的查询结果与实体框架5相结合?

时间:2013-05-04 08:08:17

标签: linq entity-framework-5

我想用一个函数用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);
                            }

                        }
                    }

                }


            }
问题是:第一次调用是ok,但是第二次报告错误:由于DbContext已被处理,操作无法完成,如何? 谢谢!

1 个答案:

答案 0 :(得分:0)

我粘贴整个代码,有些人可以运行并检查错误,谢谢你: userLocation一个表包含userid,username,userlocation(geography type)和 我是visual studio 2012中的用户数据库第一模式,并将userLocation映射到SptialTestEntities的实体。

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;
        }

    }
}