R – In ADO.Net Data Services how to check if an entity is already in the context

entity-frameworkwcf-data-services

I have an ADO.Net Data Service that I am using to do a data import. There are a number of entities that are linked to by most entities. To do that during import I create those entities first, save them and then use .SetLink(EntityImport, "NavigationProperty", CreatedEntity). Now the first issue that I ran into was that the context did not always know about CreatedEntity (this is due to each of the entities being imported independently and a creation of a context as each item is created – I'd like to retain this functionality – i.e. I'm trying to avoid "just use one context" as the answer).

So I have a .AddToCreatedEntityType(CreatedEntity) before attempting to call SetLink. This of course works for the first time, but on the second pass I get the error message "the context is already tracking the entity".

Is there a way to check if the context is already tracking the entity (context.Contains(CreatedEntity) isn't yet implemented)? I was thinking about attempting a try catch and just avoiding the error, but that seems to create a new CreatedEntity each pass. It is looking like I need to use a LINQ to Data Services to get that CreatedEntity each time, but that seems innefficient – any suggestions?

Best Answer

I think you should look at the EntityState property of your entity.

Only if it is of the value EntityState.Detached than you have to add it to your context.

Do not forget the following remark:

This enumeration has a FlagsAttribute attribute that allows a bitwise combination of its member values.

I would create a extension method:

public static class EntityObjectExtensions
{
    public static Boolean IsTracked(this EntityObject self)
    {
        return (self.EntityState & EntityState.Detached) != EntityState.Detached;
    }
}