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

I am trying to remove an object from a collection in essence, but unfortunately my code is not working. I would appreciate it if you could take a look and let me know if you can understand what I'm doing wrong. My objects are as follows:

  • Sign Person (many-to-many relationship)
  • ↔ BadgeRequirement icon (one-to-many relationship)
  • Face contains ICollection of icons.
  • Icon contains user ICollection
  • BadgeRequirement contains a Foreign Key icon

Adding and editing entries works absolutely fine.

However, when I try to remove the Icon from the Person using the code below, it does not 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(); 

Remove (badge) returns false and I cannot profile it since I am using SQL Compact 4.0

Thanks in advance for your help!

+7
source share
2 answers

This was actually allowed on one of the MSDN forums. Full details can be found here

However, as a summary, to use the Remove () method, before any changes occur, you need to load both sets from the many-many relationship. An example code is given 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 this helps someone else with similar problems.

+14
source

Had the same problem, I ended up just executing the SQL command in the join command:

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

All Articles