0

Hi I'm trying to workout a simple example of Course and Tags with Entity Framework.

One Course can have Multiple Tags associated with it (Many to Many)

What i want to achieve is a method UpdateTags( int courseId , IEnumerable<Tag> tags ). It should clear all the existing Tags (it should to maintain new order of tags) and add the new set of tags passed (it can contain both existing tags and new tags). It should create any new Tags passed (Id = 0) and only create association in the CourseTags junction table for existing Tags (Id > 0).

I tried many options came up with below.

What i came up with

static void UpdateTags(int courseId, IEnumerable < Tag > tags) {
  using(var context = new PlutoDBConnection()) {
    var c = context.Courses.Include("Tags").Single(t =>t.Id == courseId);
    foreach(var t in tags) {
      if (t.Id <= 0) {
        c.Tags.Add(t);
      }
      else {
        if (!c.Tags.Select(x =>x.Id).ToList().Contains(t.Id)) {
          c.Tags.Add(t);
        }
        context.Tags.Attach(t);
      }
    }

    var tagsToRemove = new List < Tag > ();
    foreach(var v in c.Tags) {
      if (!tags.Select(x =>x.Id).ToList().Contains(v.Id)) {
        tagsToRemove.Add(v);
      }
    }

    foreach(var b in tagsToRemove) {
      c.Tags.Remove(b);
    }

    context.SaveChanges();
  }
}

I find this as inefficient to contain many loops.

How can i achieve this with more efficiently. Is there any simpler way to do this in Entity Framework without much manual checks?

Here is my model classes

Course

public partial class Course
{
   public Course()
   {
      this.Tags = new HashSet<Tag>();
   }
   public int Id { get; set; }
   public string Title { get; set; }
   public int AuthorId { get; set; }
   public CourseLevel Level { get; set; }
   public virtual Author Author { get; set; }
   public virtual ICollection<Tag> Tags { get; set; }
}

Tag

public partial class Tag
{
   public Tag()
   {
      this.Courses = new HashSet<Course>();
   }
   public int Id { get; set; }
   public string TagText { get; set; }
   public virtual ICollection<Course> Courses { get; set; }
}
Rajeev
  • 66
  • 6

0 Answers0