I keep getting the following InvalidOperationException
:
The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.
when trying to do the following code:
newCorr.ReqCode = (from req in context.ReqCodeSet
where req.Code.Equals(requirement.Code)
select req).FirstOrDefault();
Just before this line, I am doing the following:
foreach (Requirement requirement in myInformation.Reqs)
{
MyHwReqCorr newCorr = new MyHwReqCorr();
newCorr.HwItem = Dictionaries.Instance.HwIdHwRecordDictionary[requirement.开发者_Go百科Id];
So what I'm doing is parsing through the my Information.Reqs
list, creating a new instance of MyHwReqCorr
, setting the HwItem
to an item that was stored in a dictionary earlier on, and then setting the ReqCode
by using a LINQ to SQL command which to look in a table for a req code that matches the one I'm passing in. Any help would be greatly appreciated. Any info you need, I'd be happy to provide.
EDIT: Right before I call this foreach, I can call this (as testing to verify that I can access the db):
List<ReqCode> reqCodeList = (from req in context.ReqCodeSet select req).ToList();
And I never get any errors with that. But when I try to set an item in that list (using the where extension method like:
newCorr.ReqCode = reqCodeList.Where(t=>t.Code == requirement.Code).FirstOrDefault();
or using a dictionary as done similar to the newCorr.HwItem, I get the main error.
EDIT2: I have also noticed something weird happening: When I initially run, with any setup (my original or the variable method or the method Rony posted), it works. But any subsequent run, meaning if I stop debugging and start debugging again, it fails with that error. Only when I kill all instances of excel (which is running in the background generating a log for viewing later on) and wait about 2-3 minutes, does it work again and then follows the same situation as before...passing the first time, failing immediate subsequent times.
EDIT3: It's definitely not Excel related as I prevented Excel from starting and I still get that error. But I did notice that if I wait some time, and try again, it works....sometimes.
Are you retrieving all items on the same thread/context? Try retrieving the items on same thread.
newCorr.ReqCode = (from req in context.ReqCodeSet
where req.Code equals requirement.Code
select req).FirstOrDefault();
OR
newCorr.ReqCode = context.ReqCodeSet
Where( r => r.Code == requirement.Code)
.FirstOrDefault();
精彩评论