Deserialize/import fails for newly added entity

Jan 31, 2011 at 2:35 AM

I am able to use the export and import extensions successfully for entities already on the server, but when I try to add a new entity to my context it will not import back to the context. It serializes fine, but when I try to deserialize and import it I get the error: 'MyEntity : null' cannot be added to cache because it doesn't have a valid identity.

The new entity has a valid value for the key field and I even get the error when none of the entity fields are null.

When I deserialized the entity state set and convert it to entity list I can see the new entity was there with all correct values, but it throws the InvalidOperation exception on the import call.

Is it not possible to import new entities that were not submitted to the server?

Jan 31, 2011 at 8:49 PM
Edited Jan 31, 2011 at 8:50 PM

Update: I was able to get my new entity to import back to the context with some hard coding:


DataContractSerializer dcs = new DataContractSerializer(typeof(List<EntityStateSet>));
List<EntityStateSet> result = dcs.ReadObject(isfs);
foreach (EntityStateSet ess in result) {
	MyEntity newMyEntity = new MyEntity();
	if ((ess.OriginalState == null)) {
		newMyEntity.ApplyState(ess.ModifiedState, null); // is this scenario not handled in the Import extension?
	} else {
		newMyEntity.ApplyState(ess.OriginalState, ess.ModifiedState);


I was looking at the source and it seems it doesn't handle the situation where the modified state is applied as the original state (aka for a new entity).

Jan 31, 2011 at 9:28 PM

I checked in what I think is the code fix. If you want to recompile the version you have with the fix, you can download the 49316 changeset ( and make the following change:


Instead of

 if (currentStateSet.ModifiedState != null)


It should have been

 if (currentStateSet.ModifiedState != null && currentStateSet.OriginalState != null)
else if (currentStateSet.ModifiedState != null)


Please let me know if this doesn't work, I am trying to get full unit testing added to find this kind of problem.

Jan 31, 2011 at 9:50 PM

Thanks for the quick response Colin,

I just tested your change in my scenario and it seems to be working perfectly.