Sunday 25 October 2015

Update Navigation property in Many-to-Many Entity using DBContext













I have seen that many people getting trouble with updating many-many relationship in EF. In this post i will show how to update Many-to-Many Entity using DbContext. In short we will se how to navigation property in many to many relationship.















Post and Category has Many-to-Many ralationship.

This is PostTable Entity class.
[Table("PostTable")]


public class Post
{
        public Post()
        {
            this.categories = new HashSet<Category>();
        }
        [Key]
        public int PostID { get; set; }
        public string PostTitle { get; set; }

        public virtual ICollection<Category> categories { get; set; }

}

This is CategoryTable Entity Class.
[Table("CategoryTable")]
public class Category
{
        public Category()
        {
            this.posts = new HashSet<Post>();
        }
        [Key]
        public int CategoryID { get; set; }
        public string CategoryName { get; set; }

        public virtual ICollection<Post> posts { get; set; }
}


If you see database design, actually there are three tables participates in Many-to-Many relationship between PostTable and CategoryTable, PostTable, CategoryTable and PostCategoryMapping tables. PostCategoryMapping table consist PostID and CatID where both PostID and CatID is composite key (combined primary key).

Below is the update code which updates the scalar and navigation properties.
Note: To update we have to track the object.

public void Update(Post entityToUpdate)
{
using(var _context=new PostCatDbContext())
{
/* Here we are getting existing data from database (Tracking the object from database)  */
            Post existingPost = _context.Post.First(o => o.PostID == entityToUpdate.PostID);

/* Here we are removing the categories from post which is tracked */
        existingPost.categories.Except<Category>(entityToUpdate.categories).ToList().RemoveAll(c => existingPost.categories.Remove(c));

/* Now we are adding the all new categories to the tracked post object */
         entityToUpdate.categories.Except<Category>(existingPost.categories).ToList().ForEach(o => existingPost.categories.Add(o));

/* This statement adds all scalar properties which are coming from new post to the tracked existing post */
         _context.Entry(existingPost).CurrentValues.SetValues(entityToUpdate);

/* savechanges will reflect it in database means saves the data to the database */
_context.SaveChanges();
  }   
}

So, now try the above code to update many-to-many relationship entity.

No comments:

Post a Comment