EF查询返回不同查询的响应?

时间:2019-07-02 20:20:25

标签: c# .net entity-framework

当我在多个任务中运行EF查询时,某些查询会返回另一个查询的响应。

我们的Microservices体系结构负担很重,某些服务具有较旧的体系结构,在使用完DataContext后无法正确处理。然后碰巧我们遇到了以下查询问题,它返回了另一个查询的响应。

TestContext context = new TestContext();
var results = context.Tests.First(t => t.Id == 1);

List<Task> todo = new List<Task>();
int done = 0;
int exception = 0;
int failed = 0;

for (int i = 0; i < 1000; i++)
{
    //Test newTest = GenerateAddTask(context, todo, i);

    //GenerateRemoveTask(context, todo, newTest);

    Task getItemTask = new Task(() =>
    {
        try
        {

            Test test = context.Tests.First(t => t.Id == 1);

            if (test.Id == 1 && test.Name == "test1")
            {
                done++;
            }
            else
            {
                failed++;
                throw new System.Exception("Found it");
            }
        }
        catch
        {
            exception++;
            context = new TestContext();
        }

    });

    Task getItemTask2 = new Task(() =>
    {
        try
        {

            Test test = context.Tests.First(t => t.Id == 2);

            if (test.Id == 2 && test.Name == "test2")
            {
                done++;
            }
            else
            {
                failed++;
                throw new System.Exception("Found it");
            }
        }
        catch
        {
            exception++;
            context = new TestContext();
        }

    });

    todo.Add(getItemTask);
    todo.Add(getItemTask2);
}

Parallel.ForEach(todo, new ParallelOptions { MaxDegreeOfParallelism = 100 },
t =>
{
    t.Start();
});

Task.WaitAll(todo.ToArray());

在上面的代码中,我创建了一个包含以下数据的数据库

|  Id  |  Name  |
|  1   |  test1 |
|  2   |  test2 |

当我要求ID为1的行时,我期望第一行,但有时会收到第二个响应。

在我们的系统中,这甚至更糟,因为我们拥有大量数据,并且几乎不可能追踪哪个查询返回的错误值。

0 个答案:

没有答案