While working with Parallel programming in C# 4.0 together with Entity Framework, I faced a problem. I found that trying to do some lambda expression to query the entity model inside a parallel for or parallel foreach does not actually work. It may give different error at different time. All the error will occur at runtime. During compile time, you will not get any problem.
I tried to run the following code. Trying to find out a specific test object searching it with its id. Of course I was trying to do it inside a parallel for block.
Entities db = new Entities();
PP.Parallel.For(0, 10, i =>
{
List<TEST> tests = db.TESTs.Where(t => t.TEST_ID == i).ToList();
if (tests.Count != 0)
{
Console.WriteLine("{0}", tests[0].TEST_ID);
}
});
Sometimes you may get the following error:
EntityException was unhandled by user code
The underlying provider failed on Open.

Sometimes the following:
MappingException was unhandled by user code
The type 'Parallel.TEST' has been mapped more than once.

public ObjectSet<TEST> TESTs
{
get
{
if ((_TESTs == null))
{
_TESTs = base.CreateObjectSet<TEST>("TESTs");
}
return _TESTs;
}
}
private ObjectSet<TEST> _TESTs;
Now why is that and what is the resolution of this problem. The reason of this problem is very simple. Entity model does not support parallel execution. Entity object model is not thread safe. So you cannot query an entity model inside a parallel for block.
What is the solution? Very simple. Don't use it until Microsoft makes this entity model thread safe. :)