views:

1260

answers:

2

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?

+3  A: 

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;
    }
}
Davy Landman
+1  A: 

When trying to check whether the context was tracking the entity that I wanted to update (or add) I was pretty disapointed when I found that the context.Entites.Contains(currentItem) didn't work.

I got around it using:

if (context.Entities.Where(entities => entities.Entity == currentItem).Any())
{
   this.service.UpdateObject(currentItem);                    
}
James_2195
If it doesn't have, what to do. It means what is the else part?
Mohanavel