Pergunta

Is there any particular reason why adding an item to an EF4.1 collection, saving it to the database and then selecting that collection out again would produce weird results?

When I do the initial load, all the items in the collection are of a type System.Data.Entity.DynamicProxies.MyClassName_LongString, so the following select on the collection works:

var y = MyCollection.Where(x => x.ValidTo == null).First();

Yes, there is always an item in the collection which fulfills that criteria. Always.

However, if I select the collection, add a new item to it, save the changes and then on the same context select the collection again, the last item in the collection (the new one), is not a dynamic proxy, but instead is of my POCO type (Moo.Model.MyClassName).

Carrying out the same select from above on that version of the collection throws a null reference exception - even though the last item (the non-dynamic proxy one) does indeed match the criteria, which I have confirmed through watching the collection manually...

Load the collection from another context after the changes and the behaviour doesn't show itself - they are all dynamic proxies, and the select works.

Does anyone have any idea as to whats causing this behaviour?

Foi útil?

Solução

However, if I select the collection, add a new item to it, save the changes and then on the same context select the collection again, the last item in the collection (the new one), is not a dynamic proxy, but instead is of my POCO type (Moo.Model.MyClassName).

If you create the new item with the new operator it is not a proxy. And it won't become a proxy when you query it with the same context because Entity Framework checks if there is already an object with the same key attached to the object context and if yes, it doesn't create a new (proxied) object. So, your new entity will still be the same object which is not a proxy.

If you work this way you should actually create the entity as a proxy in the first place, which means that you don't use the new operator but instead the Create method of DbSet<T>:

var newEntity = dbContext.Entities.Create();

Now, newEntity is a proxy like the other entities you already have in your collection.

I don't know though why you get the exception you described (which might have to do with the mix of proxy and non-proxy objects in the same collection) but would hope that it disappears when you use the Create method instead of new.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top