简体   繁体   English

避免重复Linq待处理插入?

[英]avoiding duplication of Linq pending inserts?

I can prevent the same object from being added twice , but I still need to reference the pending id to add other related objects. 我可以防止同一对象被添加两次,但是我仍然需要引用待处理的ID来添加其他相关对象。

In the following, some disctinct items in SomeData might want to add the same person twice. 在以下内容中,SomeData中的某些不同项目可能要两次添加同一个人。 I can track that, but I still need to add the distinct item informatio to the pending person. 我可以跟踪它,但是我仍然需要向待处理人员添加不同的项目信息。 how do i manage this? 我该如何管理?

   foreach(item i in SomeData)
      {
         var x = dc.People.Where(p.someprop==a...);
         if (x=null)
         { 
           Person p = new P(..);
           dc.People.InsertOnSubmit(p);
         }
         ...
         ...
      }

      dc.Submitchanges()

Basically you need to check to see if the entity is already attached to the context. 基本上,您需要检查该实体是否已附加到上下文。 Here is an example of how you can make this work: 这是一个如何完成这项工作的示例:

public static void SafeAttachTo<T>(this ObjectContext context, string entitySetName, ref T entity) where T : class {
            ObjectStateEntry entry;
            bool isDetached;

            if (context.ObjectStateManager.TryGetObjectStateEntry(context.CreateEntityKey(entitySetName, entity), out entry)) {
                isDetached = entry.State == EntityState.Detached;
                entity = (T) entry.Entity;
            }
            else
                isDetached = true;

            if (isDetached)
                context.AttachTo(entitySetName, entity);
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM