Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove() doesn't work with many-to-many relationship in Entity Framework

I am trying to remove an object from a collection in entity framework, but unfortunately my code is failing. I would be grateful if you could have a look and let me know if you can figure out what I'm doing wrong. My objects are as follows:

  • Person <-> Badge (many-to-many relationship)
  • Badge <-> BadgeRequirement (one-to-many relationship)
  • Person contains an ICollection of Badges
  • Badge contains an ICollection of Person
  • BadgeRequirement contains a Badge Foreign Key

Adding and editing entries works absolutely fine.

However, when I try to remove a Badge from a Person using the code below, it doesn't work:

Postback event handler on example.aspx
****The person object has been loaded as part of the load event on the page****

Badge badge = BadgeHelper.getBadge(badgeID);
if (command == "Delete")
{
 PersonHelper.removeBadgeFromPerson(badge, person);
 }

 Delete method on PersonHelper class (wrapper for all processing)

 person.Badges.Remove(badge);
 DbContext.SaveChanges();

The Remove(badge) returns false and I cannot profile this as I am using SQL Compact 4.0

Thanks in advance for your help!

like image 848
Chris Avatar asked Apr 16 '11 19:04

Chris


1 Answers

This was actually resolved in one of the MSDN forums. The full details can be found on the link here

However, as a summary, to use the Remove() method, both collections in the many to many relationship need to be loaded before any changes take place. The code sample is attached below:

class Program  {
static void Main(string[] args)
{
  using (var context= new MyContext())
  {
    var post1 = context.Posts.Find(3);
    var tag1 = context.Tags.Find(2);
    context.Entry(post1).Collection("Tags").Load();
    post1.Tags.Remove(tag1);        
    context.SaveChanges();
  }
}
}
public class Post
{
  public int PostId { get; set; }
  public string PostContext { get; set; }
  public ICollection<Tag> Tags { get; set; }
}
public class Tag
{
  public int TagId { get; set; }
  public string TagContext { get; set; }
  public ICollection<Post> Posts { get; set; }
}
public class MyContext:DbContext
{
  public DbSet<Post> Posts { get; set; }
  public DbSet<Tag> Tags { get; set; }
}

I hope that this helps somebody else with similar issues.

like image 77
Chris Avatar answered Nov 11 '22 17:11

Chris