views:

102

answers:

1

Hi folks, I've a strange problem using EF1.0... my problem happenin' only during a creation and I didn't find anything on many forum's thread.

> System.InvalidOperationException: The source query for this EntityCollection or EntityReference cannot be returned when the related object is in either an added state or a detached state and was not originally retrieved using the NoTracking merge option.
   at System.Data.Objects.DataClasses.RelatedEnd.CreateSourceQuery[TEntity](MergeOption mergeOption)
   at System.Data.Objects.DataClasses.EntityCollection`1.CreateSourceQuery()
   at Microsoft.Data.EFLazyLoading.LazyEntityCollection`1.CreateSourceQuery()
   at Microsoft.Data.EFLazyLoading.LazyEntityCollection`1.LoadStubs()
   at mptradModel.ContextObjects.ChansonWrapper.AttachEntities(Chanson chanson, ChansonRequest request) in (SolutionDir)\ProjectWrapper\ContextObjects\ChansonWrapper.cs:line 115

What is the real problem? I happens when I tried to add an Entity to another entity's list during a command creation.

I.E.: aCommand.Songs.Add(new Song() { Name = "SongName" });

Thank to you guys and sorry for my english ; Im from Quebec and usualy talk french!

UPDATE #1

My line #115 in chansonwrapper (which mean "songwrapper") :

aCommand.Songs.Add(new Song() { Name = "SongName" });

UPDATE #2

Sorry, I were trying to simplify the code to write but I think its just more confusing so here is my real code :

SongWrapper songWrapper = new SongWrapper(this.m_Context);
Song song = songWrapper.Load(request.SongId);
aCommand.Songs.Add(song);

The this.m_Context for my songWrapper ensure that my song returned in in the same context of my "aCommand" or other entity that i could load later/before. This part were alrealy tested so we know it works. One things have changed, is that we moved to "LazyLoading" what we were not using before. More weird, the update works fine! Help meee :oP!

+1  A: 

This is certainly not EF 1.0. It must be 4.0 beta. I think it may be a bug in lazy loading. You're doing (from a back revision of your question) if( aCommand.songs.Count() > 0. For an entity in the added state, this should not try to lazily load the songs. But it seems to be trying to do just that. My only suggestion is to work around the bug via something like:

if ((aCommand.EntityState != EntityState.Added) 
    && (aCommand.songs.Count() > 0))

...which is a bit kludgy, or turn lazy loading off for this. If you can boil this down to a reproducible test case, you might report it to Microsoft Connect.

By the way, you should generally prefer:

if (aCommand.songs.Any())

... to Count() > 0 as it's more efficient and readable. But that's irrelevant here.

Craig Stuntz
Well thanks. Today we've tried more things and we modify the way we create our entities so we're bypassing the problem and its clear enough. But thanks for the "Any" which is lot more clear than count as you said.
Simon