title: Entity Framework: Avoiding Inserting Duplicates
body: <p>Say, I have the following conceptual model, there are strories that have tags (more than one, so it's a many-to-many relationship), plus each tag belongs to a particular category.</p>
  
  <p>My data comes from an external source and before inserting it I want to make sure that no duplicated tags are added.</p>
  
  <p><strong>Updated code snippet:</strong></p>
  
  <pre><code>static void Main(string[] args)
      {
          Story story1 = new Story();
          story1.Title = "Introducing the Entity Framework";
          story1.Tags.Add(new Tag { Name = ".net",  });
          story1.Tags.Add(new Tag { Name = "database" });
  
          Story story2 = new Story();
          story2.Title = "Working with Managed DirectX";
          story2.Tags.Add(new Tag { Name = ".net" });
          story2.Tags.Add(new Tag { Name = "graphics" });
  
          List&lt;Story&gt; stories = new List&lt;Story&gt;();
          stories.Add(story1);
          stories.Add(story2);
  
          EfQuestionEntities db = new EfQuestionEntities();
  
          Category category = (from c in db.Categories
                               where c.Name == "Programming"
                               select c).First();
  
          foreach (Story story in stories)
          {
              foreach (Tag tag in story.Tags)
              {
                  Tag currentTag = tag;
                  currentTag = GetTag(tag.Name, category, db);
              }
  
              db.Stories.AddObject(story);
          }
  
          db.SaveChanges();
      }
  
      public static Tag GetTag(string name, Category category, EfQuestionEntities db)
      {
          var dbTag = from t in db.Tags.Include("Category")
                      where t.Name == name
                      select t;
  
          if (dbTag.Count() &gt; 0)
          {
              return dbTag.First();
          }
  
          var cachedTag = db.ObjectStateManager.GetObjectStateEntries(EntityState.Added).
              Where(ose =&gt; ose.EntitySet == db.Tags.EntitySet).
              Select(ose =&gt; ose.Entity).
              Cast&lt;Tag&gt;().Where(x =&gt; x.Name == name);
  
          if (cachedTag.Count() != 0) 
          {
              return cachedTag.First();
          }
  
          Tag tag = new Tag();
          tag.Name = name;
          tag.Category = category;
  
          db.Tags.AddObject(tag);
  
          return tag;
      }
  </code></pre>
  
  <p>However, I get an exception about an object with the same EntityKey that is already present in the ObjectContext.</p>
  
  <p>Also, if I remove the else statement I will get an exception about violating an FK constraint, so it seems like its Category attribute is set to null.</p>