Insert/Update many to many with Generic Repository
<p>I have problem with insert and update by Generic Repository, in generic insert or update it hasnot problem but in many to many relation i am getting error at insert :</p>

<p><strong>An entity object cannot be referenced by multiple instances of IEntityChangeTracker.</strong></p>

<p>update:</p>

<p><strong>The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.</strong></p>

<p>my codes are </p>

<p><em>Interface</em></p>

<pre><code> public interface IGenericRepository&lt;TEntity&gt;:IDisposable
    {
 void Insert(TEntity entity);
 void Update(TEntity entity);
}
</code></pre>

<p><em>Generic class</em></p>

<pre><code>  public class GenericRepository&lt;TEntity&gt; : IGenericRepository&lt;TEntity&gt; where TEntity : class
            {
                private ApplicationDbContext context=null;
                private DbSet&lt;TEntity&gt; dbSet=null;
                public GenericRepository()
                {
                    this.context = new ApplicationDbContext();
                    this.dbSet = context.Set&lt;TEntity&gt;();
                }
                public GenericRepository(ApplicationDbContext context)
                {
                    this.context = context;
                    this.dbSet = context.Set&lt;TEntity&gt;();
                }

                public virtual void Insert(TEntity entity)
                {
Error is here---&gt;  this.context.Set&lt;TEntity&gt;().Add(entity);
                   // dbSet.Add(entity);
                    context.SaveChanges();
                }

                public virtual void Update(TEntity entity)
                {
Error is here---&gt;   dbSet.Attach(entity);
                    context.Entry(entity).State = EntityState.Modified;
                    context.SaveChanges();
                }

        }
</code></pre>

<p><em>and control codes are</em></p>

<pre><code>        private IGenericRepository&lt;Blog&gt; _Repository = null;
        private IGenericRepository&lt;BlogTag&gt; _RepositoryTag = null;
        private IGenericRepository&lt;BlogCategory&gt; _RepositoryCategory = null;

        public BlogsController()
        {

            this._Repository = new GenericRepository&lt;Blog&gt;(new DbContext());
            this._RepositoryTag = new GenericRepository&lt;BlogTag&gt;(new DbContext());
            this._RepositoryCategory = new GenericRepository&lt;BlogCategory&gt;(new DbContext());
        }

     public async Task&lt;ActionResult&gt; Create([Bind(Include = "BlogID,BlogTitle,BlogContent,VisitCount,Preview")] Blog blog
                ,string[] SelectedTags,string[] SelectedCategories, HttpPostedFileBase files)
            {

                if (SelectedTags != null)
                {
                    blog.BlogTags = new List&lt;BlogTag&gt;();
                    foreach (var tag in SelectedTags)
                    {
                        var tagToAdd = _RepositoryTag.GetById(int.Parse(tag));
                        blog.BlogTags.Add(tagToAdd);
                    }
                }
                if (SelectedCategories != null)
                {
                    blog.BlogCategories = new List&lt;BlogCategory&gt;();
                    foreach (var cat in SelectedCategories)
                    {
                        var catToAdd = _RepositoryCategory.GetById(int.Parse(cat));
                        blog.BlogCategories.Add(catToAdd);
                    }
                }

                if (ModelState.IsValid)
                {
                    blog.DateTimeInsert = DateTime.UtcNow;
                    blog.DateTimeModify = DateTime.UtcNow;
                    blog.ImagePath= files != null ? Path.GetFileName(files.FileName) : "";
                    blog.BlogContent = HttpUtility.HtmlEncode(blog.BlogContent);

                    _Repository.Insert(blog);

                    return RedirectToAction("Index");
                }

                ViewBag.BlogTags = new SelectList(_RepositoryTag.Get(), "BlogTagID", "TagName");
                ViewBag.BlogCategories = new SelectList(_RepositoryCategory.Get(), "BlogCategoryID", "CategoriesName");

                return View(blog);
            }


            [HttpPost]
            [ValidateAntiForgeryToken]
            public async Task&lt;ActionResult&gt; Edit([Bind(Include = "BlogID,BlogTitle,BlogContent,VisitCount,Preview")] Blog blog
               , string[] SelectedTags, string[] SelectedCategories, HttpPostedFileBase files)
            {

                if (Request["BlogID"] == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                int id = int.Parse(Request["BlogID"].ToString());
                var blogsToUpdate =  _Repository.Query(i =&gt; i.BlogID == id, null).Include(t =&gt; t.BlogTags).Include(t =&gt; t.BlogCategories).Single();

                if (TryUpdateModel(blogsToUpdate, "",
                   new string[] { "BlogID", "BlogTitle", "BlogContent", "VisitCount","Preview" }))
                {
                    try
                    {


                        UpdateInstructorCourses(SelectedTags, SelectedCategories, blogsToUpdate);

                        blogsToUpdate.DateTimeModify = DateTime.UtcNow;
                        blogsToUpdate.DateTimeInsert = DateTime.UtcNow;
                        blogsToUpdate.BlogContent = HttpUtility.HtmlEncode(blogsToUpdate.BlogContent);

                        await _Repository.UpdateAsync(blogsToUpdate,  d =&gt; d.BlogTitle, d =&gt; d.VisitCount, d =&gt; d.BlogContent, d =&gt; d.ImagePath);

                        return RedirectToAction("Index");
                    }
                    catch (RetryLimitExceededException /* dex */)
                    {
                        //Log the error (uncomment dex variable name and add a line here to write a log.
                        ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
                    }
                }
                AssignedDDLCHKBoxValues(blogsToUpdate);
                return View(blogsToUpdate);
            }

            private void UpdateInstructorCourses(string[] SelectedTags, string[] SelectedCategories, Blog blogsToUpdate)
            {
                if (SelectedTags == null)
                {
                    blogsToUpdate.BlogTags = new List&lt;BlogTag&gt;();
                    return;
                }
                if (SelectedCategories == null)
                {
                    blogsToUpdate.BlogCategories = new List&lt;BlogCategory&gt;();
                    return;
                }

                var SelectedTagsHS = new HashSet&lt;string&gt;(SelectedTags);
                var SelectedCategoriesHS = new HashSet&lt;string&gt;(SelectedCategories);
                var blogTags = new HashSet&lt;int&gt;(blogsToUpdate.BlogTags.Select(c =&gt; c.BlogTagID));

                foreach (var tag in _RepositoryTag.Get())
                {
                    if (SelectedTagsHS.Contains(tag.BlogTagID.ToString()))
                    {
                        if (!blogTags.Contains(tag.BlogTagID))
                        {
                            blogsToUpdate.BlogTags.Add(tag);
                        }
                    }//if
                    else
                    {
                        if (blogTags.Contains(tag.BlogTagID))
                        {
                            blogsToUpdate.BlogTags.Remove(tag);
                        }
                    }//else
                }//foreach tag


                var blogcategories = new HashSet&lt;int&gt;
                   (blogsToUpdate.BlogCategories.Select(c =&gt; c.BlogCategoryID));
                foreach (var Category in _RepositoryCategory.Get())
                {
                    if (SelectedCategoriesHS.Contains(Category.BlogCategoryID.ToString()))
                    {
                        if (!blogcategories.Contains(Category.BlogCategoryID))
                        {
                            blogsToUpdate.BlogCategories.Add(Category);
                        }
                    }//if
                    else
                    {
                        if (blogcategories.Contains(Category.BlogCategoryID))
                        {
                            blogsToUpdate.BlogCategories.Remove(Category);
                        }
                    }//else
                }//foreach skill
            }
</code></pre>