开发者

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 ev开发者_如何学编程ent 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!


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.


Had the same issue, I ended up just executing a raw SQL command against the join table:

DbContext.Database.ExecuteSqlCommand("DELETE FROM [dbo].[Badges_Persons] WHERE Badge_Id=5000 AND Person_Id=1000");
DbContext.SaveChanges();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜