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).
所以我在尝试调用SetLink之前有一个.AddToCreatedEntityType(CreatedEntity).这当然是第一次工作,但在第二次传递时,我收到错误消息"上下文已经跟踪实体".
有没有办法检查上下文是否已经跟踪实体(context.Contains(CreatedEntity)尚未实现)?我正在考虑尝试捕获并只是避免错误,但这似乎每次传递都会创建一个新的CreatedEntity.看起来我需要使用LINQ to Data Services来每次都获得CreatedEntity,但这看起来效率不高 - 有什么建议吗?
我认为您应该查看实体的EntityState属性.
仅当它具有值EntityState.Detached时才必须将其添加到上下文中.
不要忘记以下评论:
此枚举具有FlagsAttribute属性,该属性允许按位组合其成员值.
我会创建一个扩展方法:
public static class EntityObjectExtensions { public static Boolean IsTracked(this EntityObject self) { return (self.EntityState & EntityState.Detached) != EntityState.Detached; } }